2015-10-19 120 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

請在這裏評論我的錯誤,而不是簡單地向下投票。閱讀規則 –

相關問題