【问题标题】:How can I pass a scope variable into a directive's `tAttrrs` object?如何将范围变量传递给指令的 `tAttrrs` 对象?
【发布时间】:2026-01-14 19:10:01
【问题描述】:

好的,所以我想在动态生成的模板 url 中使用范围变量。所以我尝试了这个:

html

<my-directive type="{{ type }}"></my-directive>

js

angular.module('myApp', [])
  .directive('myDirective', function () {
    return {
      templateUrl: function (tElement, tAttrs) {
        return 'templates/myDirective.' + tAttrs.type + '.html';
      };
    };
  });

我原以为tAttrs.type 会返回$scope.type 的值,但我最终得到了{{ type }}。这导致了 templates/myDirective.{{ type }}.html 的 templateUrl。

那么,我可以做些什么来获取范围变量的值而不是原始文本?

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    不能从指令的 templateUrl 中访问范围值。属性尚未编译,因此在此上下文中无法访问范围。

    这是一个可能对您有用的解决方法。

    See Plunkr

    我在这里所做的是使用包含带有 ng-include 的 div 的模板,通过双向绑定获取 url。

    【讨论】:

    • 很好,谢谢,比我想走的路线要容易得多。仍然不完美,但可以使用。
    最近更新 更多