简体   繁体   中英

How to get all form elements when the DOM is ready?

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.

FYI: I'm using ng-switch and some ng-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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM