我在互联网上到处寻找,试图弄清楚为什么在使用jQuery.Select2和ui-select2指令时,专有的AngularJS验证不起作用--这是一个错误吗??
编辑:好的,我发现只有标签输入才会发生,我的Select下拉菜单和文本输入都工作得很好。
这是小提琴http://jsfiddle.net/whiteb0x/ftEHu/
Html:
<form name="myForm" ng-controller="Ctrl">
userType: <input ui-select2="version1" class="input-xlarge" type="hidden" name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}} wtf???????!!!</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}} huh????</tt><br>
<tt>myForm.$valid = {{myForm.$valid}} | please hand me a gun :)</tt><br>
<tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
</form>Javascript:
var app = angular.module('myApp', ['ui.directives']);
function Ctrl($scope) {
$scope.userType = '';
$scope.version1 = {
tags : null
};
}发布于 2013-03-02 17:08:51
我认为select2指令在ngModel和select2插件之间传递值的方式有问题。
简而言之,当没有选择标记时,UI的select2指令将set the model to [] (空数组),因为这是select2插件对空的多选输入返回的默认值(请参阅the docs for select2数据方法)
我会在Github上发布一个问题来证实这一点,但在此期间,这里是a workaround
function Ctrl($scope) {
$scope.userType = null;
$scope.version1 = {
tags : null
};
$scope.$watch('userType', function(userType){
if(angular.isArray(userType) && userType.length === 0){
$scope.userType = '';
}
});
}或者你可以使用这个自定义的'required-multiple‘指令,它将在验证模型时考虑到空数组:
app.directive('requiredMultiple', function() {
function isEmpty(value) {
return angular.isUndefined(value) || (angular.isArray(value) && value.length === 0) || value === '' || value === null || value !== value;
}
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
});发布于 2013-11-11 18:54:06
对于标签,我一直使用的解决方案是在输入上设置ng-minlength="1"。看起来已经足够好了。
https://stackoverflow.com/questions/15170286
复制相似问题