4

it is possible to read the scope into templateUrl of directive?

I want to do something like this :

mDirective.directive('directive', [function () {
    return {
        restrict: 'A',
        scope: {
            types :'=types'
        },

templateUrl:'.mytemplate/'+scope.types+'.html'

1 Answer 1

7

Scope is not available in the directive's templateUrl. There is a feature request on github for this: Either add scope to attributes that are passed to templateUrl function or preprocess attributes based on scope parameters.

Here are two options (the second being the more general purpose):

Attribute: Scope isn't available. But the raw attributes are. So, if the raw attribute works for you, for instance if it's just a static string like this:

<div directive types="test1"></div>

Then we can pass a function into templateUrl. The second parameter will be the attributes, so you can construct a template URL with that string like this:

templateUrl: function(elem, attrs){ return ('mytemplate/'+attrs.types+'.html')},

But this doesn't work if types may change, so a better solution for you is likely:

ngInclude You can reference a scope variable inside an ngIncludesource expression. So instead of using templateURL we use template and then let ngInclude handle the setting/changing the template:

template: '<div ng-include src="\'mytemplate/\'+types+\'.html\'"></div>',

You could also manually compile and add your template inside the directive. But using ngInclude is easy and also enables animation.

demo plunker showing both options, and with a couple buttons to toggle the template and see ngInclude switch.

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.