在角度服务中使用call和bind

时间:2016-08-04 13:54:18

标签: javascript angularjs angular-services

我正在学习angularjs,我想知道一些事情。 一个用户如何调用或应用将回调函数的值连接到服务中的值。让我解释一下。

app.service("AppService"), function(){
    //value to be bound
    this.value;

    //function that references a promise or something
    this.doThing = function(){
        //refer to a promise

        externalPromise("string").then(function(response){ 
            //The scope has changed so "this" is no longer refering to the service
            this.value = response;
        });
    }

})

app.controller("AppCtrl", function(AppService){

    alert(AppService.value);

})

我知道这可以(也可能是)可以完成:

app.service("AppService"), function(){
    //value to be bound
    var value;

    //function that references a promise or something
    var doThing = function(){
        //refer to a promise

        externalPromise("string").then(changeValue(response));
    }

    function changeValue(response){
        value = response;
    }
    var getValue = function(){return value}

    return {
        value: getValue,
        doThing: doThing
    }
})



app.controller("AppCtrl", function(AppService){

        alert(AppService.value);

    })

但如果服务点是他们返回“this”那么我认为利用它最有意义。我认为可以使用call bind或apply将changeValue函数内的this设置为与控制器中的this相同。我无法弄明白具体如何。有人知道吗?即使没有必要,也可以将其视为学术活动。

编辑:在另一个问题中提供的解决方案是有效的并且可行。但是我想知道是否有一种特定的方式来做角度。在我想要绑定的函数上使用angular.bind()建议的标记为正确的答案。

1 个答案:

答案 0 :(得分:1)

您应该能够使用angular.bind为您的处理程序功能提供正确的"这个":

 this.doThing = function(){
   externalPromise("string").then(angular.bind(this, function(response){ 
        //this is now the "this" you expect
        this.value = response;
    }));
 }

常用的另一种方法是存储"这个"在变量中,然后在处理程序中使用该变量:

this.doThing = function(){
   var self = this;
   externalPromise("string").then(function(response){ 
        //self is now the "this" you wanted.
        self.value = response;
    });
 }