Javascript ES6中的AngularJS组件

Javascript ES6中的AngularJS组件,javascript,angularjs,ecmascript-6,ngcordova,Javascript,Angularjs,Ecmascript 6,Ngcordova,我在ES6中创建了一个AngularJS组件,如下所示: import template from 'template.html' class ctrler { constructor ($scope, $cordovaDevice) { $scope.title = 'This is from component' this.$scope = $scope document.addEventListener('deviceready', this.onDevice

我在ES6中创建了一个AngularJS组件,如下所示:

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 }
我的问题是
$scope
$cordovaDevice
构造函数(){}
中的本地参数,但我希望它们成为全局参数,所以我使用
这个。$scope=scope
,它不起作用


怎么办?

实际上,
$scope
不是局部参数,而是全局参数

ondevicerady()
函数是事件侦听器的回调函数,因此
这个$scope
表示不
ctrler.$scope
,这就是问题所在

谢谢你的回复并阅读我的问题


祝您愉快。

我很确定问题在于您如何将回调传递到
document.addEventListener()
。传入方法时,通过向方法添加对
bind(this)
的调用,可以将
this
绑定到控制器的上下文

试试这个:

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

执行此操作时,
this.$scope
将在执行回调时正确引用
ctrler
this.$scope

可能重复的不是ctrler.$scope,而是this.$scope,首先。为了获得正确的上下文,应该绑定回调。抱歉,这是我的键入错误,实际上我使用了
this.$scope
,但仍然无法工作。