Issue
I want to get all form elements (input, textarea, etc.) to add a function to all of these elements on blur.
Since the DOM is not loaded yet, I get an undefined for most elements. I tried to add
$scope.$watch('$viewContentLoaded
but that didn't work because I don't use ngView and I don't need ngView.
It works when I add a delay on the timeout, but this is not the best solution because the loading may differ on different environments
I tried:
angular.element(document).ready
but this also didn't get the elements.
This is the code which works, but not the best solution:
$timeout(() => {
const allFormElements = $element[0].querySelectorAll('input, textarea');
const formElement= angular.element(allFormElements[0]);
formElement.on('blur', function() {
console.log('THis is blur');
});
}, 500);
Is there a better solution instead of using timeout with a delay to fix this, without adding the function manually to all fields.
FYI: I'm using ng-switch
and some ng-if
statements to show specific input fields. Maybe this is the issue. But I don't know.
Solution
FYI: I'm using
ng-switch
and someng-if
statements to show specific input fields. Maybe this is the issue.
To add a function to all <input>
elements, define it as a directive:
app.directive("input", function() {
return {
restrict: "E",
link: postLink
};
function postLink(scope, elem, attrs) {
elem.on('blur', function(ev) {
console.log('THis is blur', ev.target);
});
}
});
Directives such as ng-repeat
, ng-switch
, ng-view
, ng-include
and ng-if
all add elements to the DOM at various times. The AngularJS framework invokes the postLink
function for directives when it adds such elements to the DOM.
For more information, see
Answered By - georgeawg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.