How to dynamically add a directive to all input elements in AngularJS across controllers & modules

。_饼干妹妹 提交于 2019-12-06 12:27:12

问题


I want to add a directive dynamically to all my textboxes in all my controllers & forms. I got a hack from here : How to dynamically add a directive to an input element in AngularJS

but in my case: there are around 200+ forms spread across different controllers & modules & it will be very time consuming to add it everywhere.

Is there an easier or more elegant way to do it ?

Edit: What I want to do ? I want to remove all leading & trailing spaces entered by user in all input boxes.


回答1:


Angular can have multiple directives with the same name, and will apply them all to the element. Create another input directive with the desired behavior (demo):

  .directive('input', function($compile) {
    return {
      restrict: 'E',
      require: '?ngModel',
      link: function(scope, elem, attrs, ngModel) {
        if (!ngModel) {
          return;
        }

        ngModel.$parsers.push(function(value) {
          return value.trim();
        });
      }
    }
  });



回答2:


If you have any common class in your all forms yo can create a controller with that class name

.directive('form-class',function($compile){
    return{
        restrict: 'C',
        link: function(scope, elem, attrs){
        }
    }
})



回答3:


The solution used by me to solve the problem (Extension of Ori Dori's answer) :

app.directive('input', function () { 
    return {
        require: '?ngModel',
        link: function (scope, element, attr, ngModelCtrl) {

            if (ngModelCtrl) {

                if (element.attr('type') == 'radio' || element.attr('type') == "file" || 
                    element.attr('type') == "checkbox" || element.attr('type') == "submit")
                {
                    //ignore them                    
                    return;
                }

                element.bind("change", function () {
                    if (element.val()) {
                        ngModelCtrl.$setViewValue(element.val().trim());
                        ngModelCtrl.$render();
                    }
                });
            }
        }
    };
});


来源:https://stackoverflow.com/questions/40080299/how-to-dynamically-add-a-directive-to-all-input-elements-in-angularjs-across-con

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!