1

$http.get().success()以下の例では、呼び出し内のコンテキストは ですundefined。「use strict;」を使っているからだと思います。そしてそれsuccess()は通常の機能です。

ただし、関数呼び出し内でサービスのコンテキストにアクセスする必要があります。これを達成する適切な方法は何ですか?

ng_app.service('database', function($http)
{
    this.db = new Db();
    this.load = function()
    {
        console.log(this); // logs the service context correctly
        $http.get('get_nodes/').success(function(ajax_data)
        {
            console.log(this); // logs "undefined"
            console.log(this.db); // throws an exception because this is undefined
            this.db.nodes = ajax_data; // throws an exception because this is undefined
        });
    }
});
4

2 に答える 2

2

通常、コンテキスト変数を設定します。

this.db = new Db();
var that = this;
this.load = function()
{
    console.log(this); // logs the service context correctly
    $http.get('get_nodes/').success(function(ajax_data)
    {
        console.log(that); 
        console.log(that.db); 
        that.db.nodes = ajax_data; 
    });

jQuery$.ajaxにはcontextプロパティがあることは知っていますが、そのようなものが Angulars$httpに存在するかどうかはわかりません。これが私が行ってきたことです。

于 2013-10-17T17:13:58.877 に答える