5

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?

SoftTimur
  • 5,630
  • 38
  • 140
  • 292
  • "this" scope inside yout addListener is your globalScope and not your local.. you should copy yout scope to a var... – guijob Jul 07 '17 at 02:37
  • Every function has its own `this` context. It doesn't look to me like you're not binding `this` to anything, so in this case it's probably `window`. – 4castle Jul 07 '17 at 02:37
  • https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Daniel Jul 07 '17 at 02:37
  • this answer shows other ways to solve this ´´this´´ issue: https://stackoverflow.com/a/20279485/6351322 – guijob Jul 07 '17 at 03:06

1 Answers1

3

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()
        })
    }
developer_hatch
  • 15,898
  • 3
  • 42
  • 75
  • @4castle uuuh! my bad! thanks a lot for show to me that mistake! you are huge ;) – developer_hatch Jul 07 '17 at 02:42
  • This helped me. However, I had to declare the function inside the constructor like in [this example](https://stackoverflow.com/a/44658351/1369235) and also had to use `self.button = function()` while declaring the `button` function. – Himanshu May 02 '22 at 08:37