从指令模板函数访问Angular作用域

7
我有一个指令,其中包含一个用于模板的函数。
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) {

从模板函数中访问指令作用域是否可能?我想做类似于:

if (scope.columnType == 'test'){ .. }

因为我希望基于其他值来呈现不同的模板。

3
不,这是不可能的;指令作用域最早可在预链接函数或控制器中使用。 - Nikos Paraskevopoulos
你将在那个模板中做什么...我们可能会采用不同的方法。 - Pankaj Parkar
1
我正在尝试根据预先计算的内容显示不同的DOM元素。 - LucianRadu
看一下这个..它和你想要的一样,在这里http://stackoverflow.com/a/30672887/2435473 - Pankaj Parkar
1个回答

11

您可以从Link函数中访问指令$ scope,$compile任何HTML并将其附加到指令元素上(事实上,该元素可以被初始化为空):

您可以从Link函数中访问指令$ scope,$compile任何HTML并将其附加到指令元素上(事实上,该元素可以被初始化为空):

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")。否则我无法使其正常工作。


谢谢,这很有帮助。 - gtiwari333

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接