指令模板函数的角度访问范围 [英] Angular access scope from directive template function
本文介绍了指令模板函数的角度访问范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有模板功能的指令
I have a directive which has a function for template
restrict: 'E', // 'A' is the default, so you could remove this line
scope: {
field : '@field',
},
template: function( element, attrs) {
//some code here
},
link: function (scope, element, attrs) {
是否可以从模板函数访问指令的范围?我正在尝试做类似
Is it possible to access the directive's scope from the template function? I'm trying to do something like
if (scope.columnType == 'test'){ .. }
因为我想基于其他值渲染不同的模板
because I want to render a different template based on other values
推荐答案
您可以从Link函数访问指令$ scope,$ compile任何HTML并将其附加到指令元素(实际上,它可能被初始化为空): / p>
You can access the directive $scope from the Link function, $compile any HTML and append it to the directive element (that in fact, could have being initialized as empty):
angular.module("example")
.directive('example', function($compile) {
return {
restrict: 'E',
link: function(scope, element, attrs){
scope.nums = [1, 2, 3];
var html = '<div ng-model="scope"><p ng-repeat="n in nums">{{ n }}</p></div>';
var el = $compile(html)(scope);
element.append(el);
}
}
});
请注意,我必须明确指定标签的数据模型(ng-model =scope )。我不能让它工作。
Notice that I had to explicitly specify the data model for the tag (ng-model = "scope"). I couldn't make it work otherwise.
这篇关于指令模板函数的角度访问范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文