I'm currently working on a form that utilizes AngularJS and Bootstrap for validation. Everything was functioning properly until I introduced typeahead functionality - the validation no longer triggers when selecting values from typeahead.
Is there a way to ensure that the field still validates even when using typeahead?
See it in action: View JS Fiddle Here
Code Snippet:
<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>
Additional CSS Styling:
input.ng-invalid{
background-color: #fdd !important;
}
input.ng-valid{
background-color: #dfd !important;
}
Extra JavaScript Code:
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()
});
}
};
});