【发布时间】:2015-01-14 14:17:39
【问题描述】:
在我们的应用程序中,我们使用“controller as”语法:
<div class="workspace-header" ng-controller="LoginController as loginCtl">
要定义 LoginController,我们将其定义为 TypeScript 类:
class LoginController {
// variables here
constructor($rootScope, $http, $location, $cookieStore, AuthService, AUTH_EVENTS, localStorageService) {
// set variables
this.$rootScope.$on(AUTH_EVENTS.logoutSuccess, () => {
this.logout();
});
}
public login(credentials: any): void {
this.AuthService.login(credentials).then(() => {
// login success
}, () => {
// login failed
});
}
public logout() {
}
}
并以这种方式实例化它:
.controller('LoginController', ['$rootScope', '$http', '$location', '$cookieStore', 'AuthService', 'AUTH_EVENTS', 'localStorageService',
($rootScope, $http, $location, $cookieStore, AuthService, AUTH_EVENTS, localStorageService) =>
new LoginController($rootScope, $http, $location, $cookieStore, AuthService, AUTH_EVENTS, localStorageService);
])
升级到 AngularJS 1.3.0 后,这根本不起作用。 “controller as”语法被完全破坏(以这种方式使用时)。我们用 ng-submit 在页面上定义一个表单:
<form name="loginForm" ng-submit="loginCtl.login(dc.credentials)" novalidate>
... fields here
<button type="submit">Login</button>
</form>
loginCtl.login() 什么都不做,并且没有错误输出到控制台。
经过大量调试和挖掘,我相信 AngularJS 的重大变化是这样的:
https://github.com/angular/angular.js/issues/8876 https://github.com/angular/angular.js/pull/8882(在文档中添加注释)
如果我这样修改我的控制器:
.controller('LoginController', ['$rootScope', '$http', '$location', '$cookieStore', 'AuthService', 'AUTH_EVENTS', 'localStorageService',
function ($rootScope, $http, $location, $cookieStore, AuthService, AUTH_EVENTS, localStorageService) {
var loginCtrl = new LoginController($rootScope, $http, $location, $cookieStore, AuthService, AUTH_EVENTS, localStorageService);
// since controllers always return 'this', extend 'this' with the controllers
// properties and it's prototype's properties
_.extend(this, loginCtrl);
_.extend(this, loginCtrl["__proto__"]);
}
])
然后我可以让它工作,但这看起来很混乱(我不确定是否必须在超类的情况下链接原型)。
有没有其他人遇到过这种情况并有更好的方法在 TypeScript 中定义这些类?
【问题讨论】:
-
你可以只做
.controller('LoginController', ['dep'..., LoginController]);你不需要新的,注射器会为你做的。 -
感谢您让这一点更清楚!
-
很高兴我能!不客气.. :)
标签: angularjs typescript