angularjs – Angular ng – 不需要使用自定义指令
我使用
Angularjs 1.5版来验证表单中的输入.
> ng-required用于验证所需的所有输入 但是,它不能使用呈现组合的自定义指令.组合根据传递给它的参数检索项目名为’listId’.然后,它使用ng-repeat在’lookupItems’上迭代.我想有些东西丢失了,比如ngModel.为什么以及如何实施它? 组合指令: app.directive('combo',function($http) { return { restrict: 'AE',template: '<div class="input-group"> <select ng-model="selectedItem">' + '<option ng-repeat="option in lookupItems" value={{option.ListValueID}}>{{option.Translation.Value}}</option></select>' + ' {{selectedItem}} </div>',replace: true,scope: { listId: '=',defaultItem: '=',selectedItem: '=' },controller: function($scope) { $http({ method: 'GET',url: '/home/listvalues?listid=' + $scope.listId }).then(function(response) { $scope.lookupItems = response.data; },function(error) { alert(error.data); }); },link: function(scope,element,attrs) {} }; }); html视图:迭代包含要呈现的控件类型的属性,然后根据’attribute.Required’将其设置为布尔值,这是真的. <form name="profileAttributesForm" ng-controller="metadataCtrl" class="my-form"> <div ng-repeat="a in attributes"> <div ng-if="a.DataType == 1"> <input type="text" name="attribute_{{$index}}" ng-model="a.Value" ng-required="a.Required" /> <span ng-show="profileAttributesForm['attribute_{{$index}}'].$invalid">Enter a Text</span> text : {{a.Value}} </div> <div ng-if="a.DataType == 4"> <div combo list-id="a.LookUpList" name="attribute_{{$index}}" selected-item="a.Value" ng-required="a.Required"></div> <span ng-show="profileAttributesForm['attribute_{{$index}}'].$invalid">lookup Required</span> Value from lookup: {{a.Value}} </div> </div> </form> 在表单中迭代的属性示例($scope.attributes),我提供它仅用于说明目的: [{ "AttributeID": 1,"DataType": 4,"NodeID": 0,"Name": "Name","Description": null,"LookUpList": 1,"SortAscending": false,"Required": true,"DefaultValue": "1","Order": 1,"Value": "" },{ "AttributeID": 3,"DataType": 1,"Name": "Job Title","LookUpList": 0,"DefaultValue": null,"Order": 2,{ "AttributeID": 4,"Name": "Email","Order": 3,"Value": "" }] 解决方法
为了让
ngRequired设置其验证器,它需要在同一元素上设置
ngModel以便从中获取
NgModelController,否则它将只打开或关闭所需属性而不影响父窗体.
表单状态($pristine,$valid等)不是由其HTML确定,而是由注册的NgModelControllers确定.当ngModel链接到表单内部时,会自动添加控制器. >例如,此< input required type =“text”>不会影响表单的有效性,即使它是必需的,因为它没有分配给它的ngModel. 在您的情况下,我看到两个解决方案: >简单的一个:在组合中移动ngRequired并将其添加到与ngModel相同的元素上;为此,您还需要添加一个新的范围变量,例如是必须的 你可以从阅读What’s the meaning of require: ‘ngModel’?开始 – 这是一个很棒的问题/答案,其中包含不同的例子.有关更深入的解释,请查看Using NgModelController with Custom Directives.作为旁注,在Angular 1.5中,他们改进了require的语法 – 请参阅$onInit and new “require” Object syntax in Angular components. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |