我正在启动一个新项目,并希望在ES6类中为控制器、服务和指令使用Range1.4。我能找到的最好看的代码倾向于使用某种修饰器,比如@Component,但这似乎是ES7的一个实验性特性。对于实际的角1.4应用程序,ES6中的控制器、服务和指令有哪些示例?我把我的项目设置为利用Babel来转移。
发布于 2015-07-18 15:43:43
使用角度为1.x的ES6类构建项目并不为时过早。如果您要开始一个新项目,我建议您使用角度为1.4或1.3的TypeScript或ES6。然后,您可以将其转换为ES5,这是当今所有浏览器所支持的JavaScript版本。
TypeScript是带有装饰器和类型注释的ES6。
你见过的@Component装饰器的例子可能是角2,这是TypeScript 1.5的一个特性。你今天可以用装饰器。也就是说,您可能需要编写自己的装饰器,将其转换为角1.4所期望的。今天你可能不用装修就能活下去。
使用ES6或TypeScript,您的Controller和Service类应该如下所示:
export class LoginController {
static $inject = ['dataApi'];
constructor(private dataApi: DataApi) {}
submit(login: LoginRequest) {
this.dataApi.login(login);
}
}
loginModule.controller('LoginController', LoginController);以及一项服务:
export class DataApi {
static $inject = ['$http'];
constructor($http: ng.IHttpService) {}
login(login: LoginRequest) {
return this.$http.post('/api/login', login);
}
}
loginModule.service('dataApi', DataApi);在本例中,LoginRequest是在其他地方定义的数据传输对象。
更新:指令
指令不是类,但如果您愿意,可以将它们创建为类。我更喜欢将它们创建为factories,因为它们是这样的。
var DIRECTIVE = 'mmTitle';
mmTitle.$inject = ['$window'];
function mmTitle($window: ng.IWindowService, $parse: ng.IParseService): ng.IDirective {
return {
restrict: 'A',
link: (scope, element, attrs) => {
$window.document.title = $parse(attrs[DIRECTIVE])(scope);
attrs.$observer(DIRECTIVE, value => $window.document.title = value);
}
}
}
loginModule.directive(DIRECTIVE, mmTitle);https://stackoverflow.com/questions/31492401
复制相似问题