好吧,所以我想在动态生成的模板 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 }}
>。这导致 templateUrl 为 templates/myDirective.{{ type }}.html
。
那么,我该怎么做才能获取范围变量的值而不是原始文本?
最佳答案
无法从指令的 templateUrl 内访问范围值。这些属性尚未编译,因此在此上下文中无法访问该范围。
这里有一个可能适合您的解决方法。
我在这里所做的是使用包含带有 ng-include 的 div 的模板,通过双向绑定(bind)获取 url。
关于javascript - 如何将范围变量传递到指令的 `tAttrrs` 对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25466394/