如何将范围变量传递到指令的 `tAttrrs` 对象中? [英] How can I pass a scope variable into a directive's `tAttrrs` object?
问题描述
好的,所以我想在动态生成的模板 url 中使用范围变量.所以我尝试了这个:
Alright, so I would like to use a scope variable in a dynamically generated template url. So I tried this:
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
.
I was expecting tAttrs.type
to return the value of $scope.type
, but instead I ended up getting {{ type }}
. This resulted in a templateUrl of templates/myDirective.{{ type }}.html
.
那么,我该怎么做才能获得范围变量的值而不是原始文本?
So, what can I do to get the scope variable's value instead of the raw text?
推荐答案
无法从指令的 templateUrl 中访问范围值.属性尚未编译,因此无法在此上下文中访问作用域.
Scope values are not accessible from within a directive's templateUrl. The attributes are not compiled yet, so from within this context it is not possible to access the scope.
这里有一个可能对您有用的解决方法.
Here is a workaround that might work for you.
我在这里所做的是使用一个包含带有 ng-include 的 div 的模板,通过双向绑定获取 url.
What I did here is using a template containing a div with ng-include, getting the url through a two-way bind.
这篇关于如何将范围变量传递到指令的 `tAttrrs` 对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!