Ola*_*laf 5 angularjs angularjs-directive
作为Angularjs的新手,我使用指令在Angularjs中创建文本框标签组合.它工作得很好,但我无法通过验证工作.这是一个精简的例子.
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>
Run Code Online (Sandbox Code Playgroud)
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>'
};
});
Run Code Online (Sandbox Code Playgroud)
硬编码输入 - myfield - 工作,另一个 - myfield2 - 没有(绑定,不是必需的错误消息).
我该如何告诉NG-show属性进行排序"替换"的领域中form.FIELD.$ error.required通过myfield2?
这是一个jsFiddle.
Geo*_*mas 13
问题是您的指令为指令创建了一个新范围,这个新范围无法访问父范围中的表单对象.
我想出了两个解决方案,但我怀疑有更优雅的"Angular"方式来做到这一点:
你的观点变成:
<div mydirective FIELD="myfield2" form="form" />
Run Code Online (Sandbox Code Playgroud)
和范围定义对象:
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>'
};
Run Code Online (Sandbox Code Playgroud)
我用这段代码更新了小提琴: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>'
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5800 次 |
| 最近记录: |