1

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());
            }
        },
    };
});

1 Answer 1

3

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());
            }
        },
    };
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.