最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - cannot read property 'push' of undefined - Stack Overflow

programmeradmin1浏览0评论
$scope.AddTask = function () {
    $scope.tasks.push([{
        "taskName": $scope.taskName,
        "priorty": $scope.selectedP
    }]);
};
$scope.tasks = [{
    "taskId": 1,
    "taskName": "task 1",
    "priorty": 1
}, {
    "taskId": 2,
    "taskName": "task 2",
    "priorty": 2
}, {
    "taskId": 3,
    "taskName": "task 3",
    "priorty": 3
}];

I got an error of cannot read property 'push' of undefined in angularjs

app demo :

$scope.AddTask = function () {
    $scope.tasks.push([{
        "taskName": $scope.taskName,
        "priorty": $scope.selectedP
    }]);
};
$scope.tasks = [{
    "taskId": 1,
    "taskName": "task 1",
    "priorty": 1
}, {
    "taskId": 2,
    "taskName": "task 2",
    "priorty": 2
}, {
    "taskId": 3,
    "taskName": "task 3",
    "priorty": 3
}];

I got an error of cannot read property 'push' of undefined in angularjs

app demo : http://plnkr.co/edit/ObKoQn2tZ4evgJpKQBpH?p=preview

Share Improve this question edited Apr 30, 2014 at 11:59 Satpal 133k13 gold badges167 silver badges170 bronze badges asked Apr 30, 2014 at 11:54 user3522457user3522457 2,9736 gold badges24 silver badges25 bronze badges 3
  • 5 $scope.tasks is undefined. Do $scope.tasks = [] before you call push. – Sebastian Commented Apr 30, 2014 at 11:57
  • I have no knowledge of Angular but I'm guessing you have to somewhat initialize the tasks array before adding elements to it – Raul Rene Commented Apr 30, 2014 at 11:57
  • Where is this cannot read property 'push' of undefined occurring? I don't see it in your plunkr. – CodingIntrigue Commented Apr 30, 2014 at 12:02
Add a ment  | 

2 Answers 2

Reset to default 3

your plnkr looks fine. although you should use

$scope.tasks.push({
    "taskName" : $scope.taskName,
    "priorty": $scope.selectedP
});

instead of an additional [].

See this function:

$scope.AddTask = function() {
  $scope.tasks.push([{
    "taskName": $scope.taskName,
    "priorty": $scope.selectedP
  }]);
};

You must remove [] before {} in $scope.tasks.push, they're pushing another array inside $scope.tasks and they must push an object.

发布评论

评论列表(0)

  1. 暂无评论