Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically reloading ng-repeat data in the DOM

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?

like image 819
Amal Antony Avatar asked Nov 13 '13 11:11

Amal Antony


2 Answers

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');
    }
  });
like image 142
Davin Tryon Avatar answered Oct 21 '22 16:10

Davin Tryon


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');
    }
});
like image 41
Fabien Thetis Avatar answered Oct 21 '22 17:10

Fabien Thetis