Javascript 如何初始化AngularJS中另一个数组元素内的数组元素?
“comments:[]”数组不工作。当我尝试.push()函数时,它不起作用。但是,当我尝试在其他元素(如标题、用户等)上使用push()时,它就会起作用Javascript 如何初始化AngularJS中另一个数组元素内的数组元素?,javascript,jquery,arrays,angularjs,Javascript,Jquery,Arrays,Angularjs,“comments:[]”数组不工作。当我尝试.push()函数时,它不起作用。但是,当我尝试在其他元素(如标题、用户等)上使用push()时,它就会起作用 $scope.pictures=[ { name:"/images/profile2.jpg", caption:"Food and Hunger", votes:0, User:"xyz@gmail.com", comments:[],
$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
}];
有人能帮我解决这个错误吗?我已经试过你在问题中提到的方法,效果很好。看看你是否也这样做了 html:
$scope.addcomment=function (index) {
var com=$window.prompt('Please enter your comment');
$scope.pictures[index].comments.push(com);
}
“错误”?什么错误?您面临什么错误,您能检查一下$scope.pictures[index].comments的类型吗?comments是一个数组?运行
addcomment
时,控制台上是否显示任何错误?尝试console.log()
对象以检查其是否符合预期。它工作正常,您需要动态地传递索引或manually@SusheelSingh是的,这是我的版本,只是因为我发了一个帖子,而不是因为SusheelSingh的版本有问题:请在这里评论我的错误,而不是简单地否决投票。阅读规则
<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>
(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);
}
});
})();