未捕获的类型错误:不能调用方法'push'——Angularjs
Uncaught TypeError: Cannot call method 'push' of undefined - Angularjs
有人可以看看这个代码,并帮助找出为什么我一直得到这个错误。我是angularjs的新手(尤其是服务/工厂函数的使用)。当函数和局部变量在控制器(而不是$service)中定义为$scope变量时,它工作得很好,但是因为这个函数返回的数据是多个其他控制器所需要的,所以我想减少代码冗余。
app.service('SupportService', function()
{
var locations = []; //local variable to which other elements should be added
//function to get data and update the local variable (this.locations)
this.setLocations = function()
{
var temp_location = {};
$.ajax
({
type: 'get',
url: 'myurl',
success: function(response)
{
for(var i = 0; i < response.length; i++)
{
temp_location =
{
id: response[i].id,
name: response[i].name
};
locations.push(temp_location); //this is where the error is
}
},
error: function(response)
{
}
});
}
从服务中访问位置变量的附加函数是
this.getLocations = function()
{
return locations;
}
我用来绑定数据的控制器如下
app.controller('RSVPController', function($scope,SupportService,AuthService)
{
$scope.init = function()
{
SupportService.setLocations();
}
$scope.locations = SupportService.getLocations();
});
,在视图中,我调用了这个控制器的init函数,并将值附加到select中,如下所示
<select ng-model="location" ng-options="item.name for item in locations track by item.id" required></select>
谢谢。
当你使用'this'时,你必须小心,因为在不同的作用域中,它可能指向不同的对象,你可以通过简单地删除this在闭包中放置位置。Service是单例的,它会记住的。
app.service('SupportService', function()
{
this.locations = []; //local variable to which other elements should be added
var self = this;
enter code here
//function to get data and update the local variable (this.locations)
this.setLocations = function()
{
var temp_location = {};
$.ajax
({
type: 'get',
url: 'myurl',
success: function(response)
{
for(var i = 0; i < response.length; i++)
{
temp_location =
{
id: response[i].id,
name: response[i].name
};
self.locations.push(temp_location); //this is where the error is
}
},
error: function(response)
{
}
});
}
相关文章:
- Push方法显示错误
- 为什么push方法没有'在这种情况下不起作用:[].推
- Javascript:如何对属性变量(例如var.hello.push)执行数组方法?太习惯AS3了
- 向 Firebase “push” 方法添加时间戳
- Javascript/jQuery - “无法调用未定义的方法'push'”,而它是定义的
- 对象在节点js中没有方法push
- 为什么Javascript库对数组方法(push,slice等)有本地引用
- Javascript Array.push 方法问题
- push 方法将元素添加到数组中不起作用,同时获取具有相同类的元素的 ID 和值
- 为什么我的javascript .push方法添加了太多对象
- 为什么我的 push() 方法不断在我的数组中插入一个“未定义”的元素
- Javascript的优点:无法理解方法array.push
- 对象没有方法push
- 有没有一种方法可以实现chain.push和.shift数组方法
- 未捕获的类型错误:不能调用方法'push'未定义的(d3强制布局)
- 未捕获类型错误:不能调用方法'push'在jquery-1.5.1.min.js中未定义
- 未处理的承诺拒绝:不能调用方法'push'零
- 未捕获的类型错误:不能调用方法'push'的定义
- 更新现有的键值对会抛出
- 未捕获的类型错误:不能调用方法'push'——Angularjs