简体   繁体   English

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

[英]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 因为我想根据其他值渲染不同的模板

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): 你可以从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);
        }
    }
});

Notice that I had to explicitly specify the data model for the tag (ng-model = "scope"). 请注意,我必须明确指定标记的数据模型(ng-model =“scope”)。 I couldn't make it work otherwise. 否则我无法使它工作。

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

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