0

I created a AngularJS component in ES6 like following:

import template from 'template.html'

class ctrler {
  constructor ($scope, $cordovaDevice) {
    $scope.title = 'This is from component'
    this.$scope = $scope
    document.addEventListener('deviceready', this.onDeviceReady)
  }

  onDeviceReady() {
    console.log(this.$scope)
  }

  $onDestroy () {
    document.removeEventListener('deviceready', this.onDeviceReady)
    console.log('ctrler onDestroy');
  }
}

const cpnt = {
  template: template,
  controller: ctrler
}

export { cpnt }

My question is what the $scope and the $cordovaDevice are local parameter in constructor(){}, but I want they become global parameter, so I use this.$scope = scope, it's not working.

How do I do?

Leo
  • 30
  • 1
  • 4
  • 1
    Possible duplicate of [How to access the correct \`this\` context inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Estus Flask May 23 '17 at 14:09
  • 1
    It's not ctrler.$scope but this.$scope, for starters. And callback should be bound in order to get proper context. – Estus Flask May 23 '17 at 14:10
  • Sorry, it's my typing error, actully I use `this.$scope`, but still not working. – Leo May 23 '17 at 15:56

2 Answers2

0

Actually, the $scope is not local parameter, it's global.

onDeviceReady() function is event listener's callback function, so this.$scope means not ctrler.$scope, that's the problem.

Thank you for reply and read my question.

Have a good day.

Leo
  • 30
  • 1
  • 4
0

I'm pretty sure the issue is how you're passing in the callback to document.addEventListener(). You'll want to bind this to the controller's context by adding a call to bind(this) to the method when you pass it in.

Try this:

document.addEventListener('deviceready', this.onDeviceReady.bind(this));

When you do this, this.$scope will correctly refer to ctrler's this.$scope when your callback is executed.

IAmKale
  • 3,146
  • 1
  • 25
  • 46