我正在使用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;
}
另外,如何从控制器传递 authService 和 factoryClient 以便在doCommonController中使用?
答案 0 :(得分:3)
您需要使用.call()而不是.bind(),也不要将任何值分配给无效的this
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);
}