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?
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.