我有以下问题。当我有一个带有角度的离子类时,我可以在注入它们之后访问构造函数中的角度服务:
export class HomeController {
static $inject = [
'$scope',
'$state'
];
constructor(
public $scope : any,
public $state : any
) {
this.$state.go('test');
this.$scope.changeController = this.changeController;
}
changeController() {
console.log("change controller");
};
}
但是,当我将其更改为更改控制器功能时,它不起作用
export class HomeController {
static $inject = [
'$scope',
'$state'
];
constructor(
public $scope : any,
public $state : any
) {
this.$scope.changeController = this.changeController;
}
changeController() {
console.log("change controller");
this.$state.go('test'); // Fails here
};
}
这是错误:
错误:undefined不是对象(评估'this。$ state.go')
我该怎么办?
最重要的是,它是否正确将changeController函数添加到范围中,或者是否有更简单的方法使其可用于模板?
提前谢谢
答案 0 :(得分:1)
在您的情况下,this
的值不正确,这是一个非常常见的问题,因为误解了ES6类。尝试使用lambda进行词法范围确定:
changeController = () => {
console.log("change controller");
this.$state.go('test'); // Fails here
};