我有一个表格,我正在使用 angular js 和 bootstrap。在我引入预输入之前,验证已全部设置并且工作正常 - 选择值时,不会触发验证。
即使从预先输入的值中选择值,如何让该字段进行验证?
看到它:这里的 JS Fiddle
代码...
<div ng-app="myApp" ng-controller="myCtrl">
<form action="" name="myForm">
<input type="text" name="one" ng-model="one" ng-valid-func="validator" />
<div class="warning" ng-show="!myForm.one.$valid">
<i class="icon-warning-sign"></i> One needs to be longer
</div>
<input type="text" name="two" ng-model="two" ng-valid-func="validator" class="typeahead" />
<div class="warning" ng-show="!myForm.two.$valid">
<i class="icon-warning-sign"></i> Two needs to be longer
</div>
</form>
</div>
和..
input.ng-invalid{
background-color: #fdd !important;
}
input.ng-valid{
background-color: #dfd !important;
}
和...
var app = angular.module('myApp', [])
var myCtrl = function($scope){
$scope.one = ""
$scope.two = ""
$scope.validator = function(val){
return val.length > 3
}
}
$(function(){
$('.typeahead').typeahead({
source: ['animal','alphabet','alphabot!','alfalfa']
})
})
app.directive('ngValidFunc', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
if (attrs.ngValidFunc && scope[attrs.ngValidFunc] && scope[attrs.ngValidFunc](viewValue, scope, elm, attrs, ctrl)) {
ctrl.$setValidity('custom', true);
} else {
ctrl.$setValidity('custom', false);
}
return elm.val()
});
}
};
});