简体   繁体   中英

Angular directive to execute a function after HTML element has been loaded

There is the following code in some controller:

angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect)

This code executes before "#fileInput" is loaded. I fixed it:

  $timeout(->
    angular.element(document.querySelector('#fileInput')).on('change', handleFileSelect)
  , 1000)

But it isn't a good solution, because page loading may take more than 1000 milliseconds. How can I fix it? Thanks in advance!

angular.element(document).ready(function () {
    angular.element(document.querySelector('#fileInput')).on('change', function(){
        alert('yeah!');
    });
});

The first red flag is "the following code in some controller". You shouldn't be manipulating the DOM from a controller.

Without knowing more specifics of your application (a plunkr would be helpful), the best advice would be to wrap the functionality that is using a file input in a directive. The link function of a directive will have a reference to the file input element that you can use to wire up events. You can then $emit those events so that the appropriate controller can handle them (or, alternatively, call event handler methods that you pass into the directive).

As a general rule, you should never have to use an #id selector in an angular application.

.directive('fileUpload', [function(){
    return {
        restrict: 'E',
        replace: true,
        template: '<input type="file"></input>',
        scope: {
        },
        controller: function () {
        },
        compile: function ($templateElement, $templateAttributes) {
            return function ($scope, $element, $attrs) {
                //$element is the input element
                $element.on('change', function(evt) {
                   $scope.$apply(function() {
                      $scope.$emit('fileUpload.change', evt);
                   });
                }
            };
        }
    };
}]);

Then in your markup:

<file-upload></file-upload>

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