5

Being rather new to Angularjs, I am creating textbox-label combinations in Angularjs using directives. It's working very well, but I can't get validation to work. Here is a stripped-down example.

The Html:

<form name="form" novalidate ng-app="myapp">
<input type="text" name="myfield" ng-model="myfield" required />{{myfield}}
<span ng-show="form.myfield.$error.required">ERROR MSG WORKING</span> 
<br>
<div mydirective FIELD="myfield2" />
</form>

The Javascript:

var myapp = angular.module('myapp', []);

myapp.directive('mydirective', function () {
    return {
        restrict: 'A',
        scope: { ngModel: '=' },
        template: '<input type="text" name="FIELD" ng-model="FIELD" />{{FIELD}}
        <span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
    };
});

The hard coded input - myfield - works, the other - myfield2 - doesn't (the binding does, just not the required-error message).

How do I tell the ng-show attribute to sort of "replace" FIELD in form.FIELD.$error.required by myfield2?

Here is a jsFiddle.

4

1 回答 1

14

问题是您的指令为指令创建了一个新范围,这个新范围无权访问父范围中的表单对象。

我想出了两个解决方案,尽管我怀疑有一种更优雅的“Angular”方式来做到这一点:

传递表单对象

你的观点变成:

<div mydirective FIELD="myfield2" form="form" />

以及范围定义对象:

return {
    restrict: 'A',
    scope: {
        ngModel: '=',
        form: '='
    },
    template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};

我已经用这段代码更新了小提琴:http: //jsfiddle.net/pTapw/4/

使用控制器

return {
    restrict: 'A',
    controller: function($scope){
        $scope.form = $scope.$parent.form;   
    },
    scope: {
        ngModel: '='
    },
    template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};
于 2013-06-11T20:25:48.893 回答