繁体   English   中英

ngView中ngRepeat中指令的动态templateUrl

[英]Dynamic templateUrl for directive in ngRepeat in ngView

我遇到了AngularJS的问题。 我的应用程序启动,然后通过ngRoute到达特定的ngView并调用控制器。 控制器初始化时,它将检索我的API上的数据。 这个ngView的导航系统带有使用material.angularjs.org/指令的标签。 选项卡处于活动状态时,它将列出以前收集的数据所代表的项目。 每个项目都是一个称为“ tile”的自定义指令,其模板由tile的类型确定。 这就是它停止的地方,因为模板的url由“ tile”的类型确定。 或在明显编译该指令之前调用了Directive(因此也称为templateURL)方法,突然该变量不可用。

一个例子通常胜于语言

这是显示我的示例的jsfiddle:

http://jsfiddle.net/e8zy2k4j/

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)
        }
      };

```我收到404错误/template/tile-{{myVar}}.html找不到

这个myVar计算得太晚了...

有人可以帮帮我吗 ? 谢谢 !

templateUrl函数运行时,属性值仍未插值。

因此,您需要在link时加载模板。 您可以廉价地重新使用ng-include来完成此任务:

.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";
    }
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM