作为
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中对“替换”字段进行排序?
解决方法
问题是您的指令为指令创建了一个新范围,这个新范围无法访问父范围中的表单对象.
我想出了两个解决方案,但我怀疑有更优雅的“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>' };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。