2015-07-20 36 views
0

在Angular中,可以從AJAX調用中獲取數據,並將其轉換爲放入指令模板的HTML?AngularJS指令 - 您可以爲AJAX調用中的數據設置模板嗎?

這裏低於僞示例:

App.directive('aDirective', function(){ 

    var getTemplate = function() { 
      var template = ''; 

     //Make Ajax call here 
     ... 

     angular.forEach(content_from_ajax, function (data) { 
       template += '<li>data</li>'; 
      }); 

      return template; 
     } 

      return { 
      restrict: "E", 
      template: getTemplate(); 
      }; 
    }); 

HTML:

<ul> 
<a-directive></a-directive> 
</ul> 

這個例子將顯示任意長度列表。

我該怎麼做呢?

+0

雖然理論上可行,但這不是使用角度的預期方式。使用帶有ng-repeat指令的現有模板會更好。 –

回答

1

僅僅因爲您正在編寫指令,您不應該忘記正常的Angular事件(如基於數據的模板)是如何完成的。

換句話說,您好像從後端接收到一組數據,並且想要將數據呈現在列表中。 ng-repeat是不是完美的工作?

App.directive('aDirective', function (AjaxService){ 
    return { 
    restrict: "E", 
    template: '<li ng-repeat="item in content_from_ajax">{{item}}</li>', 
    link: function(scope){ 
     // AjaxService here is a standin to how you get data from the backend 
     AjaxService.getData() 
        .then(function(data){ 
        scope.content_from_ajax = data; 
        }); 
    } 
}); 

ng-repeat也只是正常工作 - 即遍歷數據並生成一個模板。

此外,該指令定義對象的templatetemplateUrl性能不支持異步操作,因此異步獲取在getTemplate模板,然後使用結果與template: getTemplate()您的整個想法不會奏效。