我正在使用 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 视图:正在迭代包含要呈现的控件类型的属性,然后将其设置 ng-required 为基于“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,
"NodeID": 0,
"Name": "Job Title",
"Description": null,
"LookUpList": 0,
"SortAscending": false,
"Required": true,
"DefaultValue": null,
"Order": 2,
"Value": ""
}, {
"AttributeID": 4,
"DataType": 1,
"NodeID": 0,
"Name": "Email",
"Description": null,
"LookUpList": 0,
"SortAscending": false,
"Required": true,
"DefaultValue": null,
"Order": 3,
"Value": ""
}]