このコードを見て、なぜこのエラーが発生し続けるのか理解してもらえますか?私はangularjs(特にサービス/ファクトリ関数の使用)が初めてです。関数とローカル変数が$スコープ変数として$サービスの代わりにコントローラに定義されていてもうまくいきましたが、この関数から返されるデータは他の複数のコントローラで必要とされるため、コードの冗長性を減らしたいと思っていました。Uncaught TypeError:未定義のメソッド 'push'を呼び出せません - 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;
}
iは
app.controller('RSVPController', function($scope,SupportService,AuthService)
{
$scope.init = function()
{
SupportService.setLocations();
}
$scope.locations = SupportService.getLocations();
});
を次のようにデータがバインドするために使用するコントローラとビューであるIこのコントローラの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
あなたの '$ .ajax'リクエストに' context:this 'を追加してください。 'app.service'コールバックで' this'にプロパティを追加するべきでしょうか? –
@squintこれで問題は解決しません。そうすれば、 'this'はイベントが発生した要素を参照します。 – Tushar