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'
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 ngInclude
source 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With