WebWanderer
WebWanderer

Reputation: 10897

Angular.js dynamically construct templateURL for directive

REVISION

As I have come to truly understand my question, I have modified this question in search for a better answer. Although this link was helpful for MIME types of the 'accept' attribute, my question stems deeper.

I am writing an application where I allow users to upload files, and the files must be of a specific MIME type.

The directive is used in many places, and the MIME type needs to change across these places. I need to dynamically construct the template of my directive in order to accommodate for each implementation of the directive.

Assume that I write HTML as so:

<cmc-file-upload mimeType="text/html" ng-if="reportFileUploadSettings.showFileUploader" upload-complete-callback="importReportFile(content)" ></cmc-file-upload>

I would then wish to apply that MIME type to the template of the directive:

components.directive('cmcFileUpload', function ()
{
    return {
        restrict: 'E',
        scope: {
            uploadCompleteCallback: "&",
            mimeType: "&",
        },
        replace: false,
        template: '<input type="file" id="files" name="files[]" accept="' + scope.mimeType + '" multiple /><output id="list"></output>',

Unfortunately, this code does not seem to work this way.

How can I make this work?

REFERENCE ERROR: scope is undefined...

Upvotes: 0

Views: 277

Answers (2)

dave
dave

Reputation: 64725

Change mimeType: "&", to mimeType: "@",

because you do

mimeType="text/html"

Since "text/html" is not a variable, but the raw string, you need to use @

Then, change

accept="' + scope.mimeType + '" 

to

accept="{{mimeType}}" 

because scope the variable is not defined (yet) - once Angular parses the template, it will replace mimeType with the variable.

Edit: And the final issue is that mimeType="text/html" needs to be mime-type="text/html" because in the directive when you do

mimeType: "@",

it thinks because you used camelCase it should look for mime-type

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74949

To restrict to html use this:

template: '<input type="file" accept="text/html" id="files" name="files[]" multiple /><output id="list"></output>',

a complete answer on how to use accept is here:

File input 'accept' attribute - is it useful?

Upvotes: 1

Related Questions