可有人请看看这个代码,并帮助找出原因,我不断收到此错误。我是angularjs的新手(特别是使用服务/工厂功能)。当函数和局部变量在控制器(而不是$ service)中被定义为$ scope变量时,它工作得很好,但是由于这个函数返回的数据是多个其他控制器所需要的,我想要减少代码冗余。遗漏的类型错误:无法调用未定义的方法“推” - Angularjs
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指的是发生事件的元素。在'$ .ajax'中,'this'成为ajax对象。 – Tushar
将'context:this'添加到您的'$ .ajax'请求中。虽然你确定你应该在'app.service'回调中为'this'添加属性吗? – 2016-08-18 15:19:06
@squint这不会解决问题。这样,'this'将引用事件发生的元素。 – Tushar