可有人請看看這個代碼,並幫助找出原因,我不斷收到此錯誤。我是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