繁体   English   中英

指令模板函数的角度访问范围

[英]Angular access scope from directive template function

我有一个指令,它有一个模板功能

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'){ .. }

因为我想根据其他值渲染不同的模板

你可以从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”)。 否则我无法使它工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM