[英]Creating a custom form validator on an element directive in Angular?
I have a tags
Angular element directive which operates very similarly to Stack Overflow's own 'tags' input field for questions here. 我有一个
tags
Angular元素指令,其操作与Stack Overflow自己的“标记”输入字段非常相似,以解决此处的问题。
I want to validate that the ng-model
attribute on the tag
element is an array of at least one tag and less than ten tags. 我想验证
tag
元素上的ng-model
属性是至少一个标签且少于十个标签的数组。 However, I don't want to create a separate directive to validate this, since I'll never need to validate the length of an array again. 但是,我不想创建单独的指令来对此进行验证,因为我不再需要再次验证数组的长度。 I want the logic to be self contained inside the element directive.
我希望逻辑可以自我包含在element指令内。
Here's what I've got so far: 到目前为止,这是我得到的:
angular.module("directives.tags", []).directive("tags", ["Tag", "$timeout", function(Tag, $timeout) {
return {
require: 'ngModel',
restrict: 'E',
scope: {
availableTags: '=',
selectedTags: '=ngModel',
placeholder: '@'
},
link: function($scope, element, attributes, ctrl) {
// Snip
ctrl.$validators.taglength = function(mv, vv) {
return (mv.length > 0);
}
}
}
And my directive is used like this: 我的指令是这样使用的:
<tags available-tags="data.tags" name="tags" ng-model="text.tags"></tags>
<span ng-show="writeForm.tags.$error.taglength">Invalid!</span>
But, my taglength
validator is not working, or I am otherwise not binding it correctly. 但是,我的
taglength
验证器无法正常工作,否则我无法正确绑定它。 Any ideas? 有任何想法吗?
In your template you need to refer to element name
, not to variable in your controller's scope
. 在模板中,您需要引用元素
name
,而不是在控制器scope
引用变量。 And, in your directive's isolated scope, you could use plain ngModel
. 并且,在指令的隔离范围内,可以使用纯
ngModel
。
For example: 例如:
<body ng-controller="Ctrl">
Tags: {{ usedTags | json }}
<ng-form name="writeForm">
<tags name="tags"
ng-model="usedTags"
available-tags="availableTags">
</tags>
<span class="valid"
ng-show="writeForm.tags.$valid">
Valid!
</span>
<span class="invalid"
ng-show="writeForm.tags.$error.taglength">
Invalid!
</span>
</ng-form>
<button type="button"
ng-click="changeModel()">
Change
</button>
</body>
angular.module("directives.tags", [])
.controller('Ctrl', function($scope) {
$scope.usedTags = [];
$scope.availableTags = ['a','b'];
$scope.changeModel = function() {
$scope.usedTags = $scope.usedTags.length === 0 ? ['a'] : [];
};
})
.directive("tags", function() {
return {
require: 'ngModel',
restrict: 'E',
scope: {
ngModel: '=',
availableTags: '='
},
link: function(scope, element, attributes, ctrl) {
ctrl.$validators.taglength = function() {
return scope.ngModel.length > 0;
};
}
};
});
Related plunker here http://plnkr.co/edit/SiC8wk 相关的插件在这里http://plnkr.co/edit/SiC8wk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.