Angularjs:当控件基于指令时,验证不起作用
发布时间:2020-12-17 06:54:14 所属栏目:安全 来源:网络整理
导读:作为 Angularjs的新手,我使用指令在Angularjs中创建文本框标签组合.它工作得很好,但我无法通过验证工作.这是一个精简的例子. Html: form name="form" novalidate ng-app="myapp"input type="text" name="myfield" ng-model="myfield" required /{{myfield}}
作为
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> 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>' }; }); 硬编码输入 – myfield – 工作,另一个 – myfield2 – 没有(绑定,不是必需的错误消息). 如何告诉ng-show属性在form.FIELD.$error.required myfield2中对“替换”字段进行排序? 这是一个jsFiddle. 解决方法
问题是您的指令为指令创建了一个新范围,这个新范围无法访问父范围中的表单对象.
我想出了两个解决方案,但我怀疑有更优雅的“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>' }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |