0

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?

Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76

2 Answers2

0

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>`
}
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
-2

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);
  })
  } 
}
ojus kulkarni
  • 1,877
  • 3
  • 25
  • 41
  • @PankajParkar you should definately go through [this](http://stackoverflow.com/a/14907826/4286411) – ojus kulkarni Feb 22 '16 at 09:45
  • no man..`templateUrl: '.html'` will fail..and this obivious thing that we can get `type` value inside `link` function.. but there is no need to have `$observe` on it then.. because we are accepting it using `isolated scope` already.. Though this is not what OP wants & it wouldn't solve problem which has been faced by OP – Pankaj Parkar Feb 22 '16 at 10:04
  • 2
    true.. this will not help – Bhumi Singhal Feb 22 '16 at 10:05