2015-10-19 156 views
-3
$scope.pictures=[ 
    { 
     name:"/images/profile2.jpg", 
     caption:"Food and Hunger", 
     votes:0, 
     User:"[email protected]", 
     comments:[], 
     theme:$scope.theme 
    }, 
    { 
     name:"/images/profile3.jpg", 
     caption:"The wedding day", 
     votes:0, 
     User:"[email protected]", 
     comments:[], 
     theme:$scope.theme 
    }, 
    { 
     name:"/images/profile4.jpg", 
     caption:"Mother's Care", 
     votes:0, 
     User:"[email protected]", 
     comments:[], 
     theme:$scope.theme 
}]; 

“comments:[]”数组不起作用。当我尝试.push()函数时,它不起作用。然而,当我尝试push()其他元素,如标题,用户等然后它的作品。如何初始化AngularJS中另一个数组元素内的数组元素?

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

任何人都可以帮我解决这个错误吗?

+1

_ “错误” _?什么错误? – Cerbrus

+0

你面对的是什么错误,你可以只检查typeof $ scope.pictures [index] .comments是一个数组? –

+0

运行“addcomment”时,控制台上是否显示任何错误?尝试'console.log()'对象来检查它是否如预期的那样。 – TJL

回答

-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:"[email protected]", 
      comments:[], 
      theme:$scope.theme 
     }, 
     { 
      name:"/images/profile3.jpg", 
      caption:"The wedding day", 
      votes:0, 
      User:"[email protected]", 
      comments:[], 
      theme:$scope.theme 
     }, 
     { 
      name:"/images/profile4.jpg", 
      caption:"Mother's Care", 
      votes:0, 
      User:"[email protected]", 
      comments:[], 
      theme:$scope.theme 
     }]; 
     $scope.addcomment=function (index) { 
      var com=$window.prompt('Please enter your comment'); 
      $scope.pictures[index].comments.push(com); 
     } 
    }); 
})(); 
+0

请在这里评论我的错误,而不是简单地向下投票。阅读规则 –

相关问题