在AngularJS中将数据推送到数组

Jac*_*her 1 javascript arrays angularjs

我有一个用户需要填写并提交的表格。单击“提交”按钮后,触发了一个应将数据推入数组的函数,但是我没有运气将其推入数组。需要将数据推入的阵列在另一个控制器中。

调试代码后,我发现此错误。

Cannot read property 'comments' of undefined
    at n.$scope.submitComment (app.js:167)
Run Code Online (Sandbox Code Playgroud)

JavaScript / HTML

Cannot read property 'comments' of undefined
    at n.$scope.submitComment (app.js:167)
Run Code Online (Sandbox Code Playgroud)
.controller('DishDetailController', ['$scope', function($scope) {
    var dish = {
        name: 'Uthapizza',
        image: 'images/uthapizza.png',
        category: 'mains',
        label: 'Hot',
        price: '4.99',
        description: 'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
        comments: [{
                rating: 5,
                comment: "Imagine all the eatables, living in conFusion!",
                author: "John Lemon",
                date: "2012-10-16T17:57:28.556094Z"
            }, {
                rating: 4,
                comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
                author: "Paul McVites",
                date: "2014-09-05T17:57:28.556094Z"
            }, {
                rating: 3,
                comment: "Eat it, just eat it!",
                author: "Michael Jaikishan",
                date: "2015-02-13T17:57:28.556094Z"
            }, {
                rating: 4,
                comment: "Ultimate, Reaching for the stars!",
                author: "Ringo Starry",
                date: "2013-12-02T17:57:28.556094Z"
            }, {
                rating: 2,
                comment: "It's your birthday, we're gonna party!",
                author: "25 Cent",
                date: "2011-12-02T17:57:28.556094Z"
            }

        ]
    };

    $scope.dish = dish;
}]);

.controller('DishCommentController', ['$scope', function($scope) {
    $scope.feedback = {
        author: "",
        rating: "",
        comment: "",
        feedbackDate: ""
    };
    $scope.submitComment = function() {
        $scope.feedback.feedbackDate = new Date().toISOString();
        $scope.dish.comments.push($scope.feedback);
    }
}]);
Run Code Online (Sandbox Code Playgroud)

Jee*_*Jsb 5

使用服务在控制器之间共享数据,并使用角度对象参考来更新其他控制器中的数据。

.service('sharingService', function ($injector) {
            this.sharedObject= [];

        });
Run Code Online (Sandbox Code Playgroud)

在DishDetailController中

  $scope.dish = dish;
Run Code Online (Sandbox Code Playgroud)

经过这样的使用

angular.extend(sharingService.sharedObject, $scope.dish);
Run Code Online (Sandbox Code Playgroud)

在DishCommentController中

sharingService.sharedObject.comments.push($scope.feedback);
Run Code Online (Sandbox Code Playgroud)