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.
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();
}
});
}
}
};
});
来源:https://stackoverflow.com/questions/40080299/how-to-dynamically-add-a-directive-to-all-input-elements-in-angularjs-across-con