【问题标题】:Angularjs foreach only returns one objectAngularjs foreach 只返回一个对象
【发布时间】:2015-03-16 17:47:25
【问题描述】:

这可能很简单,我忽略了它。但是我正在按类别构建过滤器,一旦用户单击一个类别,它就会更新一个范围(我的实例 $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 上?

【问题讨论】:

    标签: javascript arrays json angularjs


    【解决方案1】:
    $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;
    }
    

    【讨论】:

    • 谢谢!我已经坚持了一个小时了!如此简单的解决方案。
    【解决方案2】:

    您正在尝试修改迭代并修改 $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;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-29
      • 2019-03-22
      • 1970-01-01
      • 2022-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多