【问题标题】:How do I initialize an array element which is inside another array element in AngularJS?如何初始化 AngularJS 中另一个数组元素内的数组元素?
【发布时间】:2015-10-19 07:26:09
【问题描述】:
$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
}];

“cmets:[]”数组不工作。当我尝试 .push() 函数时,它不起作用。但是,当我在其他元素(如标题、用户等)上尝试 push() 时,它会起作用。

$scope.addcomment=function (index) {
    var com=$window.prompt('Please enter your comment');
    $scope.pictures[index].comments.push(com);
}

谁能帮我解决这个错误?

【问题讨论】:

  • “错误”?什么错误?
  • 你遇到什么错误,你能检查 typeof $scope.pictures[index].cmets 是一个数组吗?
  • 您在运行addcomment时是否有任何错误显示在控制台?尝试console.log() 对象检查是否符合预期。
  • jsfiddle.net/HB7LU/18822 工作正常,您需要动态或手动传递索引
  • @SusheelSingh 是对的,这是我的版本plnkr.co/edit/x5fY2pQRJbrI7R6UZo8F?p=preview,发布只是因为我做了 plunker,而不是 SusheelSingh 的版本有问题:P

标签: javascript jquery arrays angularjs


【解决方案1】:

我已经尝试了您在问题中提到的内容,它工作正常。看看你有没有做同样的事情。

Demo

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);
        }
    });
})(); 

【讨论】:

  • 请在这里评论我的错误,而不是简单地投反对票。阅读规则
猜你喜欢
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 2015-01-28
  • 1970-01-01
  • 2017-11-06
相关资源
最近更新 更多