javascriptangularjsthisangularjs-rootscope

TypeError: "this..." is not a function


I define hostService as follows. The senario is I call first hostService.addListener() in the controller, then the controller may emit a message by $rootSceop.$emit, hostService is supposed to handle it.

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

However, the problem is the above code raises an error:

TypeError: this.button is not a function

Does anyone know how to fix it?


Solution

  • I solve this creating a self variable with this object, then you can call it from diferent scope:

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