[英]Angular JS - Cannot push object into scope array
im sure im missing something probably very basic but cant seem to wrap my head around this issue. 我肯定我缺少一些可能非常基本的东西,但是似乎无法解决这个问题。 I am simple trying to push an object into a scope array on click. 我很容易尝试在单击时将对象推入作用域数组。 I am currently getting error: TypeError: Cannot read property 'push' of undefined(…)
我当前收到错误消息: TypeError: Cannot read property 'push' of undefined(…)
Heres an example of what I got so far: 这是到目前为止我得到的一个例子:
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
}
}
});
Here is the controller: 这是控制器:
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(…)
}
});
Anyone have anyidea what im missing? 有人有什么想法吗?
You need to initialize My_array inside the Main_scope Object 您需要在Main_scope对象中初始化My_array
app.controller('MyController', function ($scope,$q,MyService) {
$scope.Main_scope = {};
$scope.Main_scope.My_array =[];
The error is verbose and clear My_array
is not defined. 该错误是冗长的,并且My_array
。
You need to define the array in your Main_scope
variable. 您需要在Main_scope
变量中定义数组。
$scope.Main_scope = {
My_array : []
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.