在AngularJS中,如何初始化位于另一个数组元素中的数组元素

How do I initialize an array element which is inside another array element in AngularJS?

本文关键字:数组元素 另一个 AngularJS 初始化      更新时间:2023-09-26
$scope.pictures=[
    {
        name:"/images/profile2.jpg",
        caption:"Food and Hunger",
        votes:0,
        User:"xyz@gmail.com",
        comments:[],
        theme:$scope.theme
    },
    {
        name:"/images/profile3.jpg",
        caption:"The wedding day",
        votes:0,
        User:"yamini@gmail.com",
        comments:[],
        theme:$scope.theme
    },
    {
        name:"/images/profile4.jpg",
        caption:"Mother's Care",
        votes:0,
        User:"fakeid@yahoo.com",
        comments:[],
        theme:$scope.theme
}];

"comments:[]"数组不起作用。当我尝试.push()函数时,它不起作用。然而,当我尝试push()对其他元素,如标题,用户等,然后它的工作。

$scope.addcomment=function (index) {
    var com=$window.prompt('Please enter your comment');
    $scope.pictures[index].comments.push(com);
}
有谁能帮我解决这个错误吗?

我已经尝试了你在问题中提到的,它的工作很好。看看你是否也这样做了。

html:

<div data-ng-app="myApp" data-ng-controller="myCtrl">
    <div data-ng-repeat="pic in pictures">
        {{pic.comments | json }} <button ng-click="addcomment($index)">add comment</button>
    </div>
</div>

js代码:

(function() {
    var app = angular.module('myApp',[]);
    app.controller("myCtrl", function($scope,$window) {
        $scope.pictures=[
        {
            name:"/images/profile2.jpg",
            caption:"Food and Hunger",
            votes:0,
            User:"xyz@gmail.com",
            comments:[],
            theme:$scope.theme
        },
        {
            name:"/images/profile3.jpg",
            caption:"The wedding day",
            votes:0,
            User:"yamini@gmail.com",
            comments:[],
            theme:$scope.theme
        },
        {
            name:"/images/profile4.jpg",
            caption:"Mother's Care",
            votes:0,
            User:"fakeid@yahoo.com",
            comments:[],
            theme:$scope.theme
        }];
        $scope.addcomment=function (index) {
            var com=$window.prompt('Please enter your comment');
            $scope.pictures[index].comments.push(com);
        }
    });
})();