修改“this"在Angular控制器中使用bind

Modifying "this" inside Angular controller using bind

本文关键字:控制器 bind Angular this quot 修改      更新时间:2023-09-26

我正在使用Angular的新路由器组件和js。我有多个控制器,如下所示。

我要做的是对所有控制器应用一个函数,我不需要在每个控制器中都这样做吗

function HomeController (authService, factoryClient) {
    console.log ('this is home controller');
    this = doCommonController.bind(this); //generates an error
    //here this should contain currentUser, authService, logout and testVar
    console.log(this);
}

,函数为:

var doCommonController = function (authService, currentUser) {
    this.testVar = 'value';
    this.authService = authService;
    this.currentUser =  currentUser;
    this.logout = this.authService.logout;
}

另外,我如何通过authServicefactoryClient从控制器在doCommonController中可用?

你需要使用。call()而不是。bind(),也不要给这个赋任何无效的值

function HomeController(authService, factoryClient) {
    console.log('this is home controller');
    var currentUser;
    doCommonController.call(this, authService, currentUser); //generates an error
    //here this should contain currentUser, authService, logout and testVar
    console.log(this);
}