Bknapp Bknapp - 5 months ago 27
AngularJS Question

ng-click increase limit only works once and then stops working after adding one row to ng-repeat

I'm working on a ng-repeat increase limitTo button. My problem is it works once in adding a row to my feed, but then seems to revert back to the original limitTo and then stops working.

The app.js file

angular.module('app').controller('MyController', function($scope, $http) {

$http.get('externaljsonfeed').success(function(data) {
// $scope.limit = 6;
// $scope.increasePosts = function() {
// $scope.limit += 3 ;
// }
$scope.posts = data;

var limitStep = 5;
$scope.limit = limitStep;
$scope.incrementLimit = function(add) {
$scope.limit += limitStep;
};
$scope.decrementLimit = function(remove) {
$scope.limit -= limitStep;
};

});


});

The html to output the feed

<html lang="en" ng-app="app">
<body ng-controller="MyController">
<div class="row" flex-row>
<div class="small-up-1 medium-up-2 large-up-3">
<div class="column" ng-repeat="posts in posts | filter:search | limitTo: limit">
<div class="card">
<div class="image">
<a href="{{ posts.url }}" target="_blank"><img
src="{{ posts.image_thumbnail }}" alt="{{ posts.title }}" /></a>
</div>
</div>
</div>
</div>
</div>
</body>




And then the button to increase the limitTo

<button class="load-more-btn" ng-click="incrementLimit(add)">Discover More</button>


Edit:

It is now working correctly.

Answer

Now I don't have a working example in front of me, but all the variables you define inside your success handler are not going to exist anymore once the function exits.

Especially this one could cause problems:

var limitStep = 5;

Try something more along these lines, separate the function definitions, they don't need to be inside the success handler:

angular.module('app').controller('MyController', function($scope, $http) {

  $scope.limitStep = 5;
  $scope.limit = $scope.limitStep;
  $scope.incrementLimit = function() {
        $scope.limit += $scope.limitStep;
  };
  $scope.decrementLimit = function() {
        $scope.limit -= $scope.limitStep;
  };

  $http.get('externaljsonfeed').success(function(data) {
    $scope.posts = data;
  });
}

Also think about what the "add" and "remove" arguments in the incrementLimit and decrementLimit functions were and where they were defined, if at all. (I've removed them from my bit of code because I think you do not need them at all).