0

This could be something simple and I'm overlooking it. But I'm building out a filter by categories and once a user clicks a category it updates a scope (my instance $scope.productStuff) and display the objects accordingly. My problem is when I click the category it gives me back the mulitple objects in my console. Then I look at the dom and it only shows one object (and it's the last object) instead all the objects that are in my console. Here is my function:

$scope.update = function(val) {
  angular.forEach($scope.productStuff, function(item){
    if( item.s2 === val.toUpperCase()){
      $scope.productStuff = [item];
    }       
  });
}

Here is my factory that's getting the data on page load

dataFactory.getProducts().then(function(res){
  $scope.productStuff = res.data;
  $scope.loading = false;
});

So my question is why is it displaying one object in the dom and multiple objects in the console and how do I put the items on the $scope.productStuff?

0

2 Answers 2

3
$scope.update = function(val) {
  // Create an empty array
  var stuff = [];
  angular.forEach($scope.productStuff, function(item){
    if( item.s2 === val.toUpperCase() ){
      // push to our array when condition is met (filter)
      stuff.push(item);
    }       
  });
  // $scope.productStuff now contains all the filtered items
  $scope.productStuff = stuff;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I've been stuck on this for a hour now! Such an easy solution.
1

You are trying to modify iterate over and modifying $scope.productStuff too. As soon as you write:

 $scope.productStuff = [item];

only one item remains in it. try creating a new array and once done assign it to $scope.productStuff

$scope.update = function(val) {
  var tempArray = [];
  angular.forEach($scope.productStuff, function(item){
    if( item.s2 === val.toUpperCase()){
      tempArray.push(item);
    }       
  });
  $scope.productStuff = tempArray;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.