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?
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With