【发布时间】:2015-02-19 00:04:59
【问题描述】:
$scope.$watch('selectedPoll', function(newValue, oldValue){
if(newValue !== oldValue) {
$scope.arrayResult.q1 = [];
$scope.arrayResult.q2 = [];
$scope.arrayResult.q3 = [];
angular.forEach($scope.selectedPoll.questions, function(value, key) {
if (key) {
$scope.arrayResult = [];
var newArrayYes = [];
var newArrayNo = [];
for (var i = 0; i < $scope.selectedPoll.survey_data.length; i++) {
if ($scope.selectedPoll.survey_data[i][key] === "YES") {
var resultOfqYes = newArrayYes.push($scope.selectedPoll.survey_data[i]);
}
if ($scope.selectedPoll.survey_data[i][key] === "NO") {
var resultOfqNo = newArrayNo.push($scope.selectedPoll.survey_data[i]);
}
}
$scope.arrayResult.push({
value: resultOfqYes, color: "#46BFBD", highlight: "#5AD3D1",
label: "Yes"
});
$scope.arrayResult.push({
value: resultOfqNo, color: "#F7464A", highlight: "#FF5A5E",
label: "No"
});
$scope.arrayResult[key] = $scope.arrayResult;
return $scope.arrayResult[key];
}
});
}
});
});
我尝试获取三个数据集 arrayResult.q1 q2 和 q3,一个用于 selectedPoll.questions 中的每个对象,但我只得到第三个,但是当我将 console.log 放在 if 语句的末尾时,我看到了对于 angular.forEach 方法的每个对象,都有单独的 console.log。
我的问题,如果为每个对象执行“if”语句(在我的情况下是 3 次)我通过 console.log 证明的内容,为什么 angular.forEach 方法只返回 selectedPoll.questions 中最后一个对象的一个数据?
那么我应该在哪里修复它以获得三个数据集,每个对象一个由 angular.forEach 方法执行?
【问题讨论】:
-
可能是因为您正在设置 $scope.arrayResult = [];在每个循环开始时覆盖之前循环中设置的任何内容。
-
你说得对,我删除了 $scope.arrayResult = [ ],我把它放在手表后面,这样我就可以扩展它并添加 arrayResul[key].push 并且它可以工作;)谢谢
-
np...我将其设置为答案,以便您将其关闭。
标签: javascript angularjs foreach