最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamically reloading ng-repeat data in the DOM - Stack Overflow

programmeradmin0浏览0评论

I have the following code in my view:

<li ng-repeat="i in items">{{i.id}}</li>

I would like the ng-repeat to be trigged dynamically when new values are added/removed from items. As in, if a new element is added to be beginning of items then it should be dynamically rendered to the DOM at the beginning and similarly if an element is added to the end of items that item should be rendered as the last list item. Is this dynamic changing of the DOM possible in angular?

I have the following code in my view:

<li ng-repeat="i in items">{{i.id}}</li>

I would like the ng-repeat to be trigged dynamically when new values are added/removed from items. As in, if a new element is added to be beginning of items then it should be dynamically rendered to the DOM at the beginning and similarly if an element is added to the end of items that item should be rendered as the last list item. Is this dynamic changing of the DOM possible in angular?

Share Improve this question asked Nov 13, 2013 at 11:45 Amal AntonyAmal Antony 6,80715 gold badges54 silver badges77 bronze badges 2
  • Yes, should work out of the box that way. Just make sure to push and unshift into the existing array. Angular will track by reference. – Davin Tryon Commented Nov 13, 2013 at 11:47
  • As angular js provides runtime data binding so any scope value when updated lead to apply() the dom UI you can see it here docs.angularjs.org/api/ng.directive:ngController – Vinod Louis Commented Nov 13, 2013 at 11:57
Add a comment  | 

2 Answers 2

Reset to default 10

ng-repeat should work this way out of the box. However, you need to push or unshift into the array so that the correct watch will fire. Angular will track the array by reference.

Here is a working plunker.

HTML:

<html ng-app="myApp">

  <head>
    <script data-require="angular.js@*" data-semver="1.2.0" src="http://code.angularjs.org/1.2.0/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <h1>Hello Plunker!</h1>
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="add()">Add</button>
  </body>

</html>

JS:

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

myApp.controller('Ctrl', function($scope) {

    $scope.items = ['hi', 'hey', 'hello'];

    $scope.add = function() {

      $scope.items.push('wazzzup');
    }
  });

You can use $rootScope intead of $scope to set the property items.

This way the property is global and will be updated.

myApp.controller('Ctrl', function($scope, $rootScope) {

    $rootScope.items = ['hi', 'hey', 'hello'];

    $scope.add = function() {
        $rootScope.items.push('wazzzup');
    }
});
发布评论

评论列表(0)

  1. 暂无评论