Javascript Angularjs foreach只返回一个对象
这可能很简单,但我忽略了。但我正在按类别构建一个过滤器,一旦用户单击一个类别,它就会更新一个范围(我的实例$scope.productStuff),并相应地显示对象。我的问题是,当我单击类别时,它会返回控制台中的多个对象。然后我查看dom,它只显示一个对象(这是最后一个对象),而不是控制台中的所有对象。 以下是我的功能:Javascript Angularjs foreach只返回一个对象,javascript,arrays,json,angularjs,Javascript,Arrays,Json,Angularjs,这可能很简单,但我忽略了。但我正在按类别构建一个过滤器,一旦用户单击一个类别,它就会更新一个范围(我的实例$scope.productStuff),并相应地显示对象。我的问题是,当我单击类别时,它会返回控制台中的多个对象。然后我查看dom,它只显示一个对象(这是最后一个对象),而不是控制台中的所有对象。 以下是我的功能: $scope.update = function(val) { angular.forEach($scope.productStuff, function(item){
$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.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 = [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;
}
您正在尝试修改迭代并修改$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;
}
非常感谢。我已经被困在这上面一个小时了!这么简单的解决方案,谢谢!我已经被困在这上面一个小时了!这么简单的解决办法。