我有一个空数组,我只是将整数推入。但是,每当我在视图中触发此函数时console.log
s打印为空数组[ ]
:
HTML:
<div ng-repeat="color in colors">
{{color.name}} <input type="checkbox" ng-model="color_ids" ng-change="toggleColorFilter(color.id)">
</div>
角:
app.controller('IndexCtrl', ['$scope', "Product", "Color", function($scope, Product, Color) {
...
$scope.color_ids = [];
$scope.toggleColorFilter = function(color_id) {
var index = $scope.color_ids.indexOf(color_id);
if (index > -1) {
$scope.color_ids.push(color_id);
} else {
$scope.color_ids.splice(index, 1);
}
console.log($scope.color_ids);
};
}]);
答案 0 :(得分:1)
你的if
逻辑是倒退的 - 它说如果颜色ID存在 - 那么推它,否则,拼接一个不存在的值...翻转逻辑:
if (index > -1) {
$scope.color_ids.splice(index, 1);
} else {
$scope.color_ids.push(color_id);
}