TypeError: Cannot read property 'push' of undefined(…)
这是我到目前为止所得到的一个例子:
var app = angular.module('myApp', []);
app.factory('MyService', function($http, $q, $timeout){
var My_Stored_Data = {}
return {
template: function(){
var template = { data1: "", data2: "", data3: "", data4: "" }
return template
}
}
});
这是控制器:
app.controller('MyController', function ($scope,$q,MyService) {
$scope.Main_scope = {};
$scope.add_new_object = function(){
$scope.Main_scope.My_array.push(MyService.template());
//This give an error TypeError: Cannot read property 'push' of undefined(…)
}
});
任何人都有什么遗失?
答案 0 :(得分:2)
您需要在Main_scope对象
中初始化My_arrayapp.controller('MyController', function ($scope,$q,MyService) {
$scope.Main_scope = {};
$scope.Main_scope.My_array =[];
答案 1 :(得分:1)
错误很详细且未定义My_array
。
您需要在Main_scope
变量中定义数组。
$scope.Main_scope = {
My_array : []
};