我正在尝试创建一个自定义指令来根据列表验证输入字段的文本。
例如,我在控制器中定义了一个列表:
$scope.examples = [
{"name":"Jeff"},
{"name":"John"},
{"name":"Sarah"},
{"name":"Julie"}
];
我的指令看起来像这样:
.directive('customValidation', function () {
return {
restrict:'A',
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function(input){
if(input === scope[attrs.customValidation]) {
ctrl.$setValidity('customValidation', true);
return input;
}
else {
ctrl.$setValidity('customValidation', false);
return undefined;
}
});
}
};
});
所以我可以在我的视图中比较一个列表:
<form name = "form">
<ul>
<li ng-repeat="item in examples" name='list' ng-model="item.name">
{{item.name}}</li>
</ul>
<input type='text' id='input' required name='input'
custom-validation='item.name' ng-model='input2'>
<p ng-show='form.input2.$valid'>Already a name</p>
<button ng-disabled="form.$valid">Add user</button>
但我有点陷入困境,我认为我的指令需要一些调整,但我不确定。在此先感谢您的帮助!
答案 0 :(得分:0)
我在您的原始代码中添加了一些修改,它有很多错别字和误导。我将它改编为最新版本的AngularJS(1.3.x)api。
myApp.directive('customValidation', function() {
return {
restrict: 'AE',
require: 'ngModel',
scope: {
collection: '=',
property: '@'
},
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.customValidation = function(model, viewValue) {
// Check if viewValue is not empty (:
if (!ctrl.$isEmpty(viewValue)) {
// Search in the collection if the username already exist.
var tot = scope.collection.filter(function(x) {
return x[scope.property].toUpperCase() === viewValue.toUpperCase()
});
// Other user(s) with the same name has been founded.
if (tot.length > 0)
return true;
}
// Valid state.
return false;
}
}
}
});
<form name="form">
<ul>
<li ng-repeat="item in examples" name='list' ng-model="item.name">
{{item.name}}</li>
</ul>
<input type='text' id='input' required name='input' custom-validation collection="examples" property='name' ng-model='input2' />
<p ng-show='!form.input.$error.customValidation'>Already a name</p>
<button ng-disabled="form.$valid">Add user</button>
</form>
我希望这就是你要找的东西,
干杯。