0

我有一個文章容器:負載動態內容放入容器中AngularJS版本1.4

<div ng-controller="articlesCtrl" > 
    <ul id="articles-container" > 
     <li class="article"> 
      <div>Article 1</div> 
      <div>Article Text</div> 
     </li> 
     <li> 
      <div>Article 1</div> 
      <div>Article Text</div> 
     </li> 
    </ul> 
</div> 

<button ng-click="getArticles();" class="uk-button" >Get Articles</button> 

一旦按下按鈕,我收到JSON數據響應,我需要添加接收到物品的容器。

我想使用爲目的這個角度模板:

<script type="text/ng-template" id="articles-container.tpl"> 
    <div ng-bind-html="articlesContainer"> 
     <div ng-repeat="article in articles"></div> 
      <div>{{article.title}}</div> 
      <div>{{article.text}}</div> 
    </div> 
</script> 

請告訴我怎麼走我怎麼能實現的功能或在那裏我可以看到一個例子。

感謝您的提前。

回答

0

HTML:

<div ng-controller="articlesCtrl"> 
    <ul> 
     <li class="article" ng-repeat="article in articles"> 
      <h1>{{article.title}}</h1> 
      <div ng-bind-html="article.text"></div> 
     </li> 
    </ul> 
</div> 

<button ng-click="getArticles();" class="uk-button" >Get Articles</button> 

控制器:

.controller("articlesCtrl", function($scope, $http){ 
    $scope.articles = []; 
    $scope.getArticles = function(){ 
     $http.get("url").then(function(res){ 
      angular.forEach(res.data.articles, function(article){ 
       $scope.articles.push(article); 
      }); 
     }); 
    } 
}) 
+0

感謝Srujan, 這一點!它像一個魅力。 –

+0

Hi @AlexLavrik如果這個或任何答案已解決您的問題,請點擊複選標記,考慮[接受它](http://meta.stackexchange.com/q/5234/179419)。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 –

0

這聽起來像你想有一個component。請參閱下面的示例,只需將templateUrl替換爲需要鏈接引用的html文件。

(function() { 
 
    'use strict'; 
 

 
    angular 
 
    .module('exampleApp', []) 
 
    .controller('ExampleController', ExampleController); 
 

 
    function ExampleController() { 
 
    var vm = this; 
 
    vm.articles = []; 
 

 
    vm.getArticles = function() { 
 
     // you would call the article service here 
 
     vm.articles = [{ 
 
     title: 'home', 
 
     text: Math.random().toString(36) // just use a random string for demonstration purposes 
 
     }, { 
 
     title: 'about', 
 
     text: Math.random().toString(36) 
 
     }]; 
 
    }; 
 
    } 
 
})(); 
 

 
(function() { 
 
    'use strict'; 
 

 
    angular 
 
    .module('exampleApp') 
 
    .component('articles', { 
 
     bindings: { 
 
     articles: '<' 
 
     }, 
 
     template: "<div ng-repeat='article in vm.articles'> \ 
 
      <div>{{article.title}}</div> \ 
 
      <div>{{article.text}}</div> \ 
 
    </div>", 
 
     controllerAs: 'vm' 
 
    }); 
 
})();
<!DOCTYPE html> 
 
<html ng-app='exampleApp'> 
 

 
<head> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.5/angular.min.js"></script> 
 
</head> 
 

 
<body ng-controller="ExampleController as vm"> 
 
    <articles articles="vm.articles"></articles> 
 
    <button ng-click="vm.getArticles()">Get articles</button> 
 
</body> 
 

 
</html>

+0

謝謝,但我使用的是Angular 1.4。 –