I have an Angular 1.x app and I am able to successfully update the DOM via ng-repeat when adding an element to an array in the controller. However the DOM does not update when I try to remove an element.
Here is the relevant part of the view:
<ul class="pagination">
<span ng-click="page(left)">left arrow</span>
<li ng-repeat="i in range track by $index">
<a href="" id="current-page-{{ $index * 5 == beginning }}" ng-click="pageStep( $index )">{{ $index + 1 }}</a>
</li>
<span ng-click="page(right)">right arrow</span>
</ul>
In my controller I have this variable:
$scope.range = [1,2,3,4,5,6,7,8,9,10];
and here is my actual page() function:
$scope.page = function ( direction ) {
var lastnumber = $scope.range[$scope.range.length - 1];
$scope.range.push(lastnumber + 1);
$scope.range.shift();
}
If I remove the last line in the function, the shift(), then the DOM will update accordingly. However, when I add the shift() back in the the DOM will neither add the new element nor delete the old.
This function does however update the $scope.range object properly, when I print to console I see the object gets the new number added and the first number deleted. It just does not seem to update in the browser.
Any ideas?
Make sure that you pass in your ngclick page function parameter either 'left' or 'right' as string, otherwise they will be pass as variables and be undefined in the controller.
Now the main issue with the code was that you were referencing the $index in your <a>{{$index + 1}}</a>
tags, but you should be using the element itself <a>{{i}}</a>
(without adding 1). So your code was working you were just not binding the correct variable to the view.
Using the $index as you are using it might also not give you the expected behavior you want for your id and ng-click in the <a></a>
attributes.
angular.module('app', [])
.controller('myController', function($scope) {
$scope.range = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$scope.page = function(direction) {
if (direction === 'right') {
var lastnumber = $scope.range[$scope.range.length - 1];
$scope.range.push(lastnumber + 1);
$scope.range.shift();
} else if (direction === 'left') {
/// move left code
}
}
})
<div ng-app="app" ng-controller="myController">
<ul class="pagination">
<span ng-click="page('right')">></span>
<li ng-repeat="i in range track by i">
<a href="" id="current-page-{{ $index * 5 == beginning }}" ng-click="pageStep( $index )">{{ i + 1 }}</a>
</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>