Update array items in ng-repeat table in AngularJS

I have an AngularJS app that pulls data from a JSON file. Part of the data gets added in a table using ng-repeat in the details template. When I select the first object, the data that is suppose to go into the table works fine. However, when I click on another object, the data values from the previous object stays and the data values for the newly selected object gets added underneath.

How do I get the values in the table to only show when their object is selected? I am using the .push() method to insert the values so I thought .slice() in an if statement could be a solution, but no luck so far.

JS

pplApp.directive("peopleDetails", function(FindSearch) {
return {
restrict: 'E',
scope: {
  people: "=ngPeople"
},
templateUrl: 'ppl_details.html',
controller: function($scope, $element, $attrs, $templateCache, $rootScope, FindSearch) {
  $scope.likesAndDislikes = [];
  var results = [];
  var item;
  $scope.getNumber = function() {
    array = new Array($scope.people.rating)
    return array;
  }

  $scope.getLikesAndDislikes = function() {
    $scope.likeAndDislikes = [];
    results = [];

    $scope.people.Likes.forEach(function(value, key) {
      var insert = {
        'likes': value,
        'dislikes': $scope.people.Dislikes[key]
      };
      $scope.likesAndDislikes.push(insert);
    });
  }

  $scope.$watch('people', function() {
    $scope.getLikesAndDislikes();
  });
}
};
});

Here is my code in Plunker to get the full picture.

1 answer

  • answered 2018-09-22 09:33 Shantanu

    It's because you're not resetting the same likesAndDislikes array model variable. From peopleDetails directive update your method to:

    $scope.getLikesAndDislikes = function() {
        $scope.likesAndDislikes = [];
        results = [];
    
        $scope.people.Likes.forEach(function(value, key) {
          var insert = {
            'likes': value,
            'dislikes': $scope.people.Dislikes[key]
          };
          $scope.likesAndDislikes.push(insert);
        });
    }
    

    Here only thing I've updated is resetting array variable name: $scope.likesAndDislikes = []; what you misspelled & used is likeAndDislikes .

    Updated plunker Example