I am using Angular with Bootstrap. Here is the code for reference:
Thank you to @farincz for a great answer. Here are some modifications I have made to fit with my use case.
This version provides three directives:
bs-has-successbs-has-errorbs-has (a convenience for when you want to use the other two together)Modifications I have made:
element.find() for those not using jQuery, as element.find() in Angular's jQLite only supports finding elements by tagname.element.find() in a $timeout to support cases where the element may not yet have it's children rendered to the DOM (e.g. if a child of the element is marked with ng-if).if expression to check for the length of the returned array (if(input) from @farincz's answer always returns true, as the return from element.find() is a jQuery array).I hope somebody finds this useful!
angular.module('bs-has', [])
.factory('bsProcessValidator', function($timeout) {
return function(scope, element, ngClass, bsClass) {
$timeout(function() {
var input = element.find('input');
if(!input.length) { input = element.find('select'); }
if(!input.length) { input = element.find('textarea'); }
if (input.length) {
scope.$watch(function() {
return input.hasClass(ngClass) && input.hasClass('ng-dirty');
}, function(isValid) {
element.toggleClass(bsClass, isValid);
});
}
});
};
})
.directive('bsHasSuccess', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-valid', 'has-success');
}
};
})
.directive('bsHasError', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
}
};
})
.directive('bsHas', function(bsProcessValidator) {
return {
restrict: 'A',
link: function(scope, element) {
bsProcessValidator(scope, element, 'ng-valid', 'has-success');
bsProcessValidator(scope, element, 'ng-invalid', 'has-error');
}
};
});
Usage:
You can also install Guilherme's bower package that bundles all this together.