$http.put
的成功功能無法訪問其在內部調用的服務的範圍this
。我需要更新PUT請求回調中的服務屬性。使用錯誤的「this」範圍的AngularJS服務http成功功能
這是我想要的服務做了削減例如:
var myApp = angular.module('myApp', function($routeProvider) {
// route provider stuff
}).service('CatalogueService', function($rootScope, $http) {
// create an array as part of my catalogue
this.items = [];
// make a call to get some data for the catalogue
this.add = function(id) {
$http.put(
$rootScope.apiURL,
{id:id}
).success(function(data,status,headers,config) {
// on success push the data to the catalogue
// when I try to access "this" - it treats it as the window
this.items.push(data);
}).success(function(data,status,headers,config) {
alert(data);
});
}
}
很抱歉,如果有在JS的一些錯誤,主要的一點是怎樣訪問服務範圍從成功回調裏面?
編輯:而這個問題的答案是正確的,我切換到factory
方法既Josh和馬克推薦它
在這種情況下,我仍然更喜歡工廠方法,但實際上回答問題時使用+1。 :-) – 2013-02-16 18:41:37
@Josh,我更喜歡這個工廠。 – 2013-02-16 18:42:23
我打算拿出工廠的答案,但我覺得我應該選擇這個作爲正確答案,因爲它回答了問題。我肯定會對我的問題添加編輯,提及我已經訴諸了你的問題@JoshDavidMiller – 2013-02-17 21:59:26