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

China☆狼群 提交于 2019-12-04 19:12:40

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();
        });
      }
    }
  });

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){
        }
    }
})

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