在ngView指令在ngRepeat动态templateUrl [英] Dynamic templateUrl for directive in ngRepeat in ngView
问题描述
我现在面临一个问题,AngularJS。
我的应用程序启动,然后到达通过ngRoute特定ngView并调用一个控制器。
当控制器初始化检索我的API数据。
这ngView具有使用material.angularjs.org/指令标签的导航系统。当标签被激活,它会列出重新由pviously收集的数据presented $ P $项目。
每个项目是被称为瓦片,其模板由瓦片的类型确定一个定义指令。而且那里它停止,因为模板的URL由瓦片的类型确定。或指令(因此templateURL)方法被调用之前,这显然编译,顿时变量不可用。
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.
一个例子是往往胜于言
下面是的jsfiddle显示我的例子:
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
```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)
}
};
```
我得到/template/tile-{{myVar}}.html没有找到404错误
``` i get 404 error /template/tile-{{myVar}}.html not found
这myVar的计算太晚了......
This myVar is computed too late...
有人能帮帮我吗?
谢谢!
Can someone please help me ? Thanks !
推荐答案
在 templateUrl
功能运行时,该属性值仍然没有插值。
When templateUrl
function runs, the attribute values are still not interpolated.
所以,你需要在链接
的时间来加载的模板。你可以便宜地重新使用 NG-包括
来实现这一目标:
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";
}
}
});
这篇关于在ngView指令在ngRepeat动态templateUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!