Reputation: 270
I am facing a problem with AngularJS. My application starts, then reaches a specific ngView through ngRoute and calls a controller. when the controller is initialize it retrieves data on my API. this ngView has a navigation system with tabs using material.angularjs.org/ directives. When a tab is active, it lists items represented by the data previously collected. Each item is a custom directive called "tile" whose template is determined by the type of tile. And that is where it stops, since the url of the template is determined by the type of the "tile". Or the Directive (and therefore templateURL) method is called before this is obviously compiled, suddenly the variable is not available.
An example is often better than words
here is a jsfiddle showing my example:
```html
<md-list ng-if="data_array.length">
<md-item ng-repeat="data in data_array" jl-tile="{{myVar}}"></md-item>
</md-list>
```
```javascript
app.directive("jlTile",
["CurrentUser", "$compile",
function(CurrentUser, $compile){
return {
restrict: "A",
templateUrl: function(element, attrs){
console.log(attrs); // attrs show "{{myVar}}" instead of "feeder"
return "/templates/elements/tile-feeder.html"; //should return this
// return "/templates/tile-" + attrs.jlTile + ".html";
},
link: function(scope, element, attrs){
console.log(scope)
}
};
``` i get 404 error /template/tile-{{myVar}}.html not found
This myVar is computed too late...
Can someone please help me ? Thanks !
Upvotes: 0
Views: 257
Reputation: 49590
When templateUrl
function runs, the attribute values are still not interpolated.
So, you'd need to load the template at link
time. You can cheaply re-use ng-include
to accomplish that:
.directive("jlTile", function($interpolate){
return {
template: '<div ng-include="url"></div>',
link: function(scope, element, attrs){
var suffix = $interpolate(attrs.jlTile)(scope);
scope.url = "/templates/elements/tile-" + suffix + ".html";
}
}
});
Upvotes: 3