我必须跟踪angularjs中的项目数组
angular.module('app').controller('AppController', function ($scope, $timeout) {
$scope.items = {
item1: {
name: "Hamburger",
complete: "50%",
start: "2015/09/10 11:00",
finish: "2015/09/11 04:00",
work: "8 hours"
},
item2: {
name: "Pasta",
complete: "50%",
start: "2015/09/10 11:00",
finish: "2015/09/11 04:00",
work: "8 hours"
},
item3: {
name: "Potato",
complete: "80%",
start: "2015/09/10 18:00",
finish: "2015/09/11 04:00",
work: "8 hours"
}
};
$scope.items.push({
item4: {
name: "Ham",
complete: "50%"...
}
});
}
我想为它添加一个新项目,但它无效。
我尝试了.push(item)方法,但它在控制台
中失败并显示以下消息Object doesn't support property or method 'push'
将项目添加到现有数组的最简单方法是什么?
答案 0 :(得分:2)
实际上你正在使用对象(不是数组)
为对象添加值:
$scope.items[key] = value;
OR
初始化数组而不是对象
$scope.items = [....];
答案 1 :(得分:1)
您的 $ scope.items 数据不是数组,而是一个对象。您使用{ }
声明它,而object不会获得 .push()方法。
如果你想使用Array.prototype.push()方法,你必须对数组进行delcare,所以只需更改:
$scope.items = { ..... };
通过
$scope.items = [ ..... ];
所以你可以这样做:
$scope.items.push({item4 : { name: "Ham", complete: "50%"...}});
答案 2 :(得分:1)
根据您的代码$scope.items
是一个对象,而不是数组。所以$scope.items.push
会抛出错误。
您可以将$scope.items
转换为数组,也可以使用$scope.items.item4 = { name: "Ham", complete: "50%"...};
设置值。
查看您的数据结构数组更有意义,以便您可以使用数组方法。
angular.module('app').controller('AppController', function ($scope, $timeout) {
$scope.items = [{
name : "Hamburger",
complete : "50%",
start: "2015/09/10 11:00",
finish: "2015/09/11 04:00",
work: "8 hours"
}, ...];
$scope.items.push({ name: "Ham", complete: "50%"...});
});
答案 3 :(得分:0)
正如您在代码中提到的,它是一个javascript对象而不是一个数组。只有Array支持推送。声明你的数组如下:
$scope.items = [
item1 : {
name : "Hamburger",
complete : "50%",
start: "2015/09/10 11:00",
finish: "2015/09/11 04:00",
work: "8 hours"
},
item2 : {
name : "Pasta",
complete : "50%",
start: "2015/09/10 11:00",
finish: "2015/09/11 04:00",
work: "8 hours"
},
item3 : {
name : "Potato",
complete : "80%",
start: "2015/09/10 18:00",
finish: "2015/09/11 04:00",
work: "8 hours"
}
];
现在您可以推送新项目,但不会抛出错误。