2016-02-07 52 views
0

我有JSON的火力对象数组,其具有一定的键 - 值对和一个阵列,我使用的NG-重复显示这些值和材料对话框添加评论 。在该对话框中我通过从纳克重复的帖子,并附控制器的对话框中,但是当我在数组中推动评论它显示财产推不因为即使我的阵列与一个空白阵列 初始化未定义定义这里是我的app.js在一个角材料对话框操纵火力阵列

var app = angular.module('myapp', ['firebase', 'ngMaterial']); 
    app.factory("posts", ["$firebaseArray", 
        function ($firebaseArray) { 
      // create a reference to the database location where we will store our data 
      //var randomRoomId = Math.round(Math.random() * 100000000); 
      var ref = new Firebase('https://xxxxxxxxx.firebaseio.com/posts'); 

      // this uses AngularFire to create the synchronized array 
      return $firebaseArray(ref); 
      } 
           ]); 
    app.controller('mainCtrl', ['$scope', '$firebaseArray', 'posts', '$timeout', '$mdToast', '$mdDialog', function ($scope, $firebaseArray, posts, $timeout, $mdToast, $mdDialog) { 
     $scope.posts = posts; 
     $scope.post = {}; 
     $scope.loading = true; 
     $scope.showForm = false; 
     $timeout(function() { 

      $scope.loading = false; 
     }, 5000); 

     $scope.createPost = function (post) { 
      $scope.posts.$add({ 
       name: post.name, 
       desc: post.desc, 
       url: post.url, 
       like: 0, 
       dislike: 0, 
       comments: [] 
      }); 
      $scope.myForm.$setPristine(); 
      $scope.myForm.$setUntouched(); 
      $scope.post = {}; 
      $scope.showForm = false; 
      $mdToast.show(
       $mdToast.simple() 
       .textContent('Post Added !!') 
       .position("top right") 
       .hideDelay(3000) 
      ); 
     }; 
     $scope.showAddForm = function() { 
      $scope.showForm = true; 
     }; 
     $scope.clearForm = function() { 
      $scope.showForm = false; 
      $scope.myForm.$setPristine(); 
      $scope.myForm.$setUntouched(); 
      $scope.post = {}; 
     }; 

     $scope.showDialog = function (post) { 


      $mdDialog.show({ 

       templateUrl: 'dialogtemp.html', 
       locals: { 
        post: post, 
        posts: $scope.posts 

       }, 
       controller: DialogController 
      }); 
     } 

     function DialogController($scope, $mdDialog, post, posts) { 
      $scope.post = post; 
      $scope.posts = posts; 
      $scope.closeDialog = function() { 
       $mdDialog.hide(); 
      }; 
      $scope.addComment = function() { 

       $scope.post.comments.push({ 
        "by": "jain", 
        "com": "heyy" 
       }); 
       $scope.posts.$save($scope.post); 
      }; 
     }; 

       }]); 
+0

贵'$ scope.post'有评论关键已经可用。如果没有,我想你应该首先将它初始化为'$ scope.post.comments = []'。 – Saksham

+0

$ scope.post.comments是一个已经初始化为[]的数组,我初始化时,添加帖子,请看看createPost() –

+0

是啊,工作,我检查,如果数组之前推,并用[]重新分配,非常感谢! :田田:但我不明白为什么这个错误发生时,我已经分配了一个空的数组呢? –

回答

1

这可能是你的$scope.post尚未定义不comments关键。尝试使用空数组首先初始化它,然后push()(当然,使用nessesary检查)。一个简单的例子是。

var file = {};file.comments = [];file.comments.push({text:"hello"});//no error 

但是这会给你错误

var file = {};file.comments.push({text:"hello"});//error: Cannot read property 'push' of undefined(…)