4

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
  • 8,904
  • 23
  • 106
  • 212
  • "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

2

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()
        })
    }
Damián Rafael Lattenero
  • 14,625
  • 3
  • 30
  • 62