Reconcile Angular.js and Bootstrap form validation styling

前端 未结 12 2057
刺人心
刺人心 2020-12-22 18:53

I am using Angular with Bootstrap. Here is the code for reference:

12条回答
  •  抹茶落季
    2020-12-22 19:49

    Minor improvement to @farincz's answer. I agree that a directive is the best approach here but I didn't want to have to repeat it on every .form-group element so I updated the code to allow adding it to either the .form-group or to the parent element (which will add it to all contained .form-group elements):

    angular.module('directives', [])
      .directive('showValidation', [function() {
        return {
            restrict: "A",
            link: function(scope, element, attrs, ctrl) {
    
                if (element.get(0).nodeName.toLowerCase() === 'form') {
                    element.find('.form-group').each(function(i, formGroup) {
                        showValidation(angular.element(formGroup));
                    });
                } else {
                    showValidation(element);
                }
    
                function showValidation(formGroupEl) {
                    var input = formGroupEl.find('input[ng-model],textarea[ng-model]');
                    if (input.length > 0) {
                        scope.$watch(function() {
                            return input.hasClass('ng-invalid');
                        }, function(isInvalid) {
                            formGroupEl.toggleClass('has-error', isInvalid);
                        });
                    }
                }
            }
        };
    }]);
    

提交回复
热议问题