Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TemplateUrl directive: AngularJs

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'
like image 963
user880386 Avatar asked Mar 21 '23 20:03

user880386


1 Answers

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.

like image 157
KayakDave Avatar answered Apr 02 '23 14:04

KayakDave