Angularjs foreach 只返回一个对象



这可能是一件简单的事情,我忽略了它。但是我正在按类别构建过滤器,一旦用户单击类别,它就会更新范围(我的实例 $scope.productStuff)并相应地显示对象。我的问题是当我单击类别时,它会在我的控制台中返回多个对象。然后我查看 dom,它只显示一个对象(它是最后一个对象),而不是我控制台中的所有对象。这是我的函数:

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

这是我的工厂,它正在获取页面加载的数据

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

所以我的问题是为什么它在 dom 中显示一个对象,在控制台中显示多个对象,以及如何将这些项目放在 $scope.productStuff 上?

$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;
}

您正在尝试修改迭代并修改$scope.productStuff。一旦你写:

 $scope.productStuff = [item];

只剩下一个项目。 尝试创建一个新数组,完成后将其分配给 $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;
}

最新更新