我有一个json对象帖子的firebase数组,它有一些键值对和一个数组,我使用ng-repeat显示这些值和一个材质对话框来添加注释。在对话框中,我从ng-repeat传递了帖子,并将控制器附加到对话框,但是当我按下数组中的注释时,即使我的数组已初始化,也显示属性push未定义为undefined 用空白数组 这是我的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 :(得分:1)
可能是您的$scope.post
尚未定义comments
密钥。首先尝试使用空数组初始化它,然后使用push()
(当然还有必要的检查)。一个简单的例子就是。
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(…)