Bhumi Singhal
Bhumi Singhal

Reputation: 8297

Evaluate attrs in templateUrl

I need to read the value of an attr in the templateUrl function of my directive.

<my-dirc type="type"></my-dirc>

my-dirc :

return {
scope : {
  type : =
},
templateUrl: function(elem, attrs) {
  console.log(attrs.type);
}
}

however, the console return "type" only and not the value of type. i have also tried doing

<my-dirc type="{{type}}"></my-dirc>
my-dirc :

    return {
    scope : {
      type : @
    },
    templateUrl: function(elem, attrs) {
      console.log(attrs.type);
    }
    }

Now the console.log gives me {{type}}.

How can I get the value of type?

Upvotes: 0

Views: 418

Answers (2)

ojus kulkarni
ojus kulkarni

Reputation: 1907

You dont need to write type in expression
Try this

<my-dirc type="type"></my-dirc>

DIR :

return {
  scope : {
  type : '=type'
},
  templateUrl: '.html'

  'link' : function(elem, attrs) {
  attrs.$observe('type', function (obs) {
        console.log(obs);
  })
  } 
}

Upvotes: -2

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

You can't get access to scope of the parent, here inside templatUrl function. Because template/templateUrl function gets evaluated first before creating controller scope, that's the reason why you are getting raw value inside your attribute. If you have pass hardcoded value inside attribute then only you can retrieve that inside function.

This issue can only be solved using ng-include

templateUrl: function(elem, attrs) {
   return '<div ng-include="type? \'template\'+type+\'.html\': \'\'"></div>`
}

Upvotes: 0

Related Questions