2015-12-03 81 views
0

我有JSON數組我的控制之內,我想通過使用NG重複幾次,以生成使用指令,我創建。每次需要通過調用模板中的特定指令函數將數組中的數據傳遞給指令。我能夠完美地獲得我的字符串,但由於生成的模板必須是一些HTML代碼,所以Angular不解釋它。使用範圍變量使用雙大括號{{}}

如果我改變

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

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

(我加入之前 「格」 的關鍵字一些空間,讓顯示以及HTML代碼)

我有我我的HTML項目部分執行,但通常使用大括號之間的一些數據的一切都不解釋(應返回undefined或null)。我該怎麼做才能訪問這些數據和/或使指令的模板正確地生成結果?

我已經這樣做了plunker向你展示我的問題。

非常感謝你提前。

回答

0

,可以估算出您正在使用您的指令串。請注意,我正在向變量$ interpolate注入指令。下面是從角的網站的官方文檔: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); 
      } 
     } 
    }; 
}]); 
0

你返回考慮一切爲字符串,包括通過對象是getTemplate()函數的結果。你只需要使用它的實際價值:

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

這裏的plunker:http://plnkr.co/edit/N5ziwjSRDWDMEWAH9ODl?p=preview