【问题标题】:Dynamic templateUrl for directive in ngRepeat in ngViewng 视图中指令的动态 templateUrl 重复
【发布时间】:2015-04-16 17:21:43
【问题描述】:

我遇到了 AngularJS 的问题。 我的应用程序启动,然后通过 ngRoute 到达特定的 ngView 并调用控制器。 当控制器初始化时,它会在我的 API 上检索数据。 这个 ngView 有一个导航系统,带有使用 material.angularjs.org/ 指令的选项卡。 When a tab is active, it lists items represented by the data previously collected. 每个项目都是一个名为“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 not found

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

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

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

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

    【讨论】:

    • 谢谢,它解决了我的问题!祝你有美好的一天。
    猜你喜欢
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 2016-10-13
    • 2023-04-05
    相关资源
    最近更新 更多