ali khezri ali khezri - 29 days ago 14
AngularJS Question

Can not find element in angular directive?

I use an Angular directive for input file with file type, but input variable is undefined.

angular.directive("ngUpload", function() {
return {
restrict : "A",
template : '<input id="fileInput" name="file" type="file" class="ng-hide" multiple><md-button id="uploadButton" class="md-raised md-primary"> Choose Files </md-button>',
link : function (scope, element, attrs) {
var input = element.find('#fileInput');
var button = element.find('#uploadButton');

if (input.length && button.length) {
button.click((e) => input.click());
}
},
};
});

Answer

As stated in the documentation jqLite's find is limited to lookup by tag name.

So you can either include jQuery (before angular.js) to retrieve the element by id or use an alternative way to grab a hold of the input.

You don't even need an id selector since there's only one input element in your template, so this should work:

var input = element.find('input');

Also, directive is declared on a module, not on the global angular object.

Lastly, don't prefix your own directives with ng- as they may clash with (future) angular core directives.

A more complete example:

angular.module('myModule').directive("customUpload", function() {
    return {
        restrict : "A",
        template : '<input id="fileInput" name="file" type="file" class="ng-hide" multiple><md-button id="uploadButton" class="md-raised md-primary"> Choose Files </md-button>',
        link : function (scope, element, attrs) {
            var input = element.find('input');
            var button = element.find('md-button');

            if (input.length && button.length) {
                button.click((e) => input.click());
            }
        },
    };
});