TypeError:"这......"不是一个功能

时间:2017-07-07 02:35:06

标签: javascript angularjs this angularjs-rootscope

我定义hostService如下。 senario是我在控制器中首先调用hostService.addListener(),然后控制器可以通过$rootSceop.$emit发出消息,hostService应该处理它。

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()
        })
    }

然而,问题是上面的代码引发了一个错误:

TypeError: this.button is not a function

有谁知道如何修复它?

1 个答案:

答案 0 :(得分:1)

我解决这个问题,用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()
        })
    }
相关问题