簡體   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