类型错误:“这个...”不是一个函数

Sof*_*mur 5 javascript this angularjs angularjs-rootscope

我定义hostService如下。情况是我首先hostService.addListener()在控制器中调用,然后控制器可能会发出一条消息$rootSceop.$emithostService应该处理它。

app.service('hostService', ['$rootScope', function ($rootScope) {    
    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            this.button()
        })
    }
Run Code Online (Sandbox Code Playgroud)

但是,问题是上面的代码会引发错误:

TypeError: this.button is not a function
Run Code Online (Sandbox Code Playgroud)

有谁知道如何修理它?

Dam*_*ero 3

我解决了这个问题,创建一个带有this对象的自变量,然后您可以从不同的范围调用它:

app.service('hostService', ['$rootScope', function ($rootScope) {    

    var self = this

    this.button = function () {
        Office.context.ui.displayDialogAsync("https://www.google.com", {}, function () {});
    }

    this.addListener = function () {
        $rootScope.$on("message", function (event, data) {
            self.button()
        })
    }
Run Code Online (Sandbox Code Playgroud)