簡體   English   中英

通過使用雙大括號{{}}在指令模板內使用范圍變量

[英]Use scope variables within directive template by using double curly brackets {{}}

我的控制器中有一個JSON數組,我想通過使用ng-repeat生成幾次(使用我創建的指令)。 每次需要通過調用模板中特定指令的功能,將數組中的數據傳遞給指令。 我能夠完美地得到我的字符串,但是由於生成的模板必須是一些HTML代碼,因此Angular不會對其進行解釋。

如果我改變

    template: '< div ng-bind="getTemplate(thiselem)">< /div>',

對於

    template: '< div ng-bind-html="getTemplate(thiselem)">< /div>',

(我在“ div”關鍵字之前添加了一些空格,以允許同時顯示html代碼)

我在項目中執行了HTML,但是通常不會使用大括號之間的某些數據進行解釋(應返回undefined或null)。 我該怎么做才能訪問這些數據和/或使指令的模板正確生成結果?

我已經完成了此工作,以向您展示我的問題。

提前非常感謝您。

您可以插入指令中使用的字符串。 請注意,我正在向指令中注入變量$ interpolate。 以下是Angular網站上的官方文檔: AngularJS:API:$ interpolate

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.elements = [
      {id: 1, name: 'bonjour'},
      {id: 2, name: 'bonsoir'}
    ];
  $scope.text = 'Hello world';
});

app.directive("frameelement", ['$interpolate', function($interpolate) {
  return {
        restrict: 'EA',
        scope: {
            thiselem: '='
        },
        template: '<div ng-bind="getTemplate(thiselem)"></div>',
        link: function(scope, element, attrs) {
            scope.getTemplate = function(thiselem) {
                return $interpolate('<h1>{{thiselem.id}} : {{thiselem.name}} tt</h1>')(scope);
            }
        }
    };
}]);

您將返回getTemplate()函數的結果,並將所有內容視為字符串,包括傳遞的對象。 您只需要使用其實際值:

link: function(scope, element, attrs) {
    scope.getTemplate = function(thiselem) {
        return '<h1>' + thiselem.id + ':' + thiselem.name + 'tt</h1>';
    }
}

這是the客: http ://plnkr.co/edit/N5ziwjSRDWDMEWAH9ODl?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM