在AngularJS ver.1.4中将动态内容加载到容器中

时间:2016-08-16 04:09:15

标签: angularjs angularjs-directive angularjs-ng-repeat angularjs-design-patterns

我有一个文章容器:

<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数据响应,我需要将收到的内容添加到文章容器中。

我想将此Angular模板用于此目的:

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

请告诉我如何实现功能或我可以在哪里看到示例。

感谢您提前。

2 个答案:

答案 0 :(得分: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);
            });
        });
    }
})

答案 1 :(得分: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>