【发布时间】:2013-09-26 15:27:39
【问题描述】:
我有一个表单,我正在使用 angular js 和 bootstrap。在我引入预输入之前,验证已全部设置并且工作正常 - 选择值时,不会触发验证。
即使从预先输入的值中选择值,我如何才能验证字段?
看到它:JS Fiddle Here
代码...
<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()
});
}
};
});
【问题讨论】:
-
我正在使用 Angular-UI typeahead 来达到这个目的:angular-ui.github.io/bootstrap/#/typeahead 有一个 typeahead-on-select 参数在选择一个值时执行,那是你可以触发表单的时刻验证。
-
@alfrescian 我正在尝试类似的方法,但无法正常工作:jsfiddle.net/ppMz5/1
标签: javascript twitter-bootstrap angularjs