本篇记录一些AngularJS结合使用ES6的各种写法。

ES6中module的导出导入

class MainController {
constructor(searchService){
this.searchService = searchService;
} search(){
this.searchService
.fetch(this.searchTerm)
.then(response => {
this.items = resposne.data.items;
})
}
} export {MainController}

如何把module中的Controller注册进module呢?

import {MainController } from './MainController';
import {searchService } from './SeachService'; angualr
.module('app',[])
.controller('mainController', MainController)
.service('searchService', searchService);

ES6中的继承

class PageController{
constructor(name){
this.name = name;
} sayHello(){
return 'Hello ' + this.name;
}
} export {PageController}

在另外一个文件中:

import {PageController} from './PageController';

class ProductPageController extends PageController {
constructor(){
super('jack');
}
} export {ProductPageController}

最后注册到module中去:

angular
.module('app',[])
.controller('ProductPageController', ProductPageController);

ES6中Service和Controller的写法

class UserService{
constructor($http){
this.$http = $http;
} getFullName(){
return this.$http.get('api/user/details');
}
} class MyController{
//注意:定义时的class名是UserService,正真的名称是在service('realname',UserServie)中定义的
constructor(userService){
userService.getFullName().then(result => this.userName = result.fullName);
}
} angular.module('app')
.service('userService', UserService)
.controller('MyController', MyController);

ES6中Providers的写法

class MyProvider{
constructor(){
this.apiPath = 'default/api';
}
setApiPath(value){
this.apiPath = value;
}
$get($http){
return {
getThings: () => $http.get(this.apiPath);
}
}
}

ES6的Provider中依赖的注入是写在$get()中的,不能在constructor中注入。Provider中必须有$get()方法。

ES6中Factory的写法

class Thing{
constructor(){
console.log('create the thing');
showMsg();
}
showMsg(){
console.log('some msg');
}
} class ThingFactory{
constructor($timeout){
this.$timeout = $timeout;
} createThing(){
return this.$timeout(() => new Thing(),1000);
}
}

如何往module中注册呢?

● 第一种写法

angular.module('app')
.factory('thingFactory', () => new ThingFactory());

以上写法是错误的,因为$timeout还没有注入进去。可以这样写。

angular.module('app')
.factory('thingFactory', ['$timeout', ($timeout) => new ThingFactory($timeout)]);

● 第二种写法

但,以上的写法也不是最理想的。最好是写在类中。

class ThingFactory{
constructor($timeout){
this.$timeout = $timeout;
} createThing(){
return this.$timeout(() => new Thing(),1000);
}
} ThingFactory.$inject = ['$timeout'];

然后,

angular.module('app')
.factory('thingFactory', () => new ThingFactory());

● 第三种写法

class ThingFactory{
constructor($timeout){
this.$timeout = $timeout;
} createThing(){
return this.$timeout(() => new Thing(),1000);
}
} ThingFactory.$inject = ['$timeout']; var constructorFn = ThingFactory; //args = ['$timeout']
var args = constructorFn.$inject; //根据参数创建ThingFactory实例,任意多的参数
var factoryFunction = (...args) => {
return new constructorFn(...args);
} //['$timeout', ($timeout) => new ThingFactory($timeout)]
var factoryArray = args.push(factoryFunction); angular.module('app')
.factory('thingFactory', factoryArray);

ES6中Directive的写法

class MyDirective{
constructor($interval){
this.template = '<div>I\'m a directive</div>';
this.restrict = 'E';
this.scope = {};
this.$interval = $interval;
} compile(tElement){
tElement.css('position','absolute');
} link(scope, element){
this.$interval(() => this.move(element),1000);
} move(element){
element.css('left', (Math.random() * 500) + 'px');
element.css('top', (Math.random() * 500) + 'px');
}
}

以上,如果同时使用compile和link方法,link方法应该是compile的返回值。

compile(tElement){
tElement.css('position','absolute');
return this.link;
}

以上,当angular调用this.link方法,将不会在MyDirective的当前上下文中,调用this.$interval(() => this.move(element),1000);会报undefined类型错误。

如果改成这样:

compile(tElement){
tElement.css('position','absolute');
return (scope, element) => {
this.$interval(() => this.move(element),1000);
};
}

这里,当使用=>后,调用this.$interval(() => this.move(element),1000);方法能保证还MyDirective所在的当前上下文中。

还可以这么写:

compile(tElement){
tElement.css('position','absolute');
return this.link.bind(this);
} link(scope, element){
this.$interval(() => this.move(element),1000);
}

但, 以上所有的做法都必须调用compile方法,而在实际场景中,调用compile方法不是必须的。最好这样写:

var constructorFn = MyDirective;

//是否有compile方法
if (!constructorFn.prototype.compile) {
// 如果没有,通过原型创建compile方法
constructorFn.prototype.compile = () => {};
} var originalCompileFn = _cloneFunction(constructorFn.prototype.compile); //重写compile方法
_override(constructorFn.prototype, 'compile', function () {
return function () { //先调用原先的compile方法
originalCompileFn.apply(this, arguments); //如果Directive包含link方法再执行link方法,绑定正确的上下文
if (constructorFn.prototype.link) {
return constructorFn.prototype.link.bind(this);
}
};
});

往module注册controller、factory、provider等的帮助方法

Michael Bromley还专门写了一个帮助方法,在这里

大致这样使用:

class MyAngularComponent {
/*@ngInject*/
constructor(dependency1, dependency2) {
this.dependency1 = dependency1;
// stuff happens here
}
someMethods() {
this.dependency1.doThatThing();
// more stuff here
}
} register('app')
.controller('MyController', MyAngularComponent)
.service('myService', MyAngularComponent)
.provider('myOtherService', MyAngularComponent)
.factory('myFactory', MyAngularComponent)
.directive('myDirective', MyAngularComponent);

参考资料:
http://blog.thoughtram.io/angularjs/es6/2015/01/23/exploring-angular-1.3-using-es6.html
http://www.michaelbromley.co.uk/blog/350/exploring-es6-classes-in-angularjs-1-x
https://github.com/timroes/angular-es6-sample

在AngularJS中使用ES6的更多相关文章

  1. angularJS中的Promise对象($q)的深入理解

    原文链接:a better way to learn AngularJS - promises AngularJS通过内置的$q服务提供Promise编程模式.通过将异步函数注册到promise对象, ...

  2. Angularjs中的promise

    promise 是一种用异步方式处理值的方法,promise是对象,代表了一个函数最终可能的返回值或抛出的异常.在与远程对象打交道非常有用,可以把它们看成一个远程对象的代理. 要在Angular中创建 ...

  3. angularJS中XHR与promise

    angularJS应用是完全运行在客户端的应用,我们可以通过angularJS构建一个不需依赖于后端,同时能够实现动态内容和响应的web应用,angularJS提供了将应用与远程服务器的信息集成在一起 ...

  4. AngularJS中get请求URL出现跨域问题

    今天早上帮助同学看了一个AngularJS的问题,主要是请求中出现了跨域访问,请求被阻止. 下面是她给我的代码: <html lang="en" ng-app="m ...

  5. AngularJS 中的Promise --- $q服务详解

    先说说什么是Promise,什么是$q吧.Promise是一种异步处理模式,有很多的实现方式,比如著名的Kris Kwal's Q还有JQuery的Deffered. 什么是Promise 以前了解过 ...

  6. AngularJS中的表单验证

    AngularJS中的表单验证 AngularJS自带了很多验证,什么必填,最大长度,最小长度...,这里记录几个有用的正则式验证 1.使用angularjs的表单验证 正则式验证 只需要配置一个正则 ...

  7. 关于angularjs中的jQuery

    关于angularjs中的jQuery 下面是一个小例子,用来说明我经常看到的一种模式.我们需要一个开关型的按钮.(注意:这个例子的代码有点装逼,并且有点冗长,只是为了用来代表更加复杂一些的例子,这些 ...

  8. angularjs中的directive scope配置

    angularjs中的directive scope配置 定义directive其中重要的一环就是定义scope,scope有三种形式: 默认的scope,DOM元素上原有的scope scope: ...

  9. angularjs中provider,factory,service的区别和用法

    angularjs中provider,factory,service的区别和用法 都能提供service,但是又有差别 service 第一次被注入时实例化,只实例化一次,整个应用的生命周期中是个单例 ...

随机推荐

  1. spring事务详解(二)实例

    在Spring中,事务有两种实现方式: 编程式事务管理: 编程式事务管理使用底层源码可实现更细粒度的事务控制.spring推荐使用TransactionTemplate,典型的模板模式. 申明式事务管 ...

  2. linux内核环形缓冲区【转】

    转自:https://blog.csdn.net/eydwyz/article/details/56671023 循环缓冲区在一些竞争问题上提供了一种免锁的机制,免锁的前提是,生产者和消费 都只有一个 ...

  3. 远程不能访问CentOS的tomcat 8080端口

    一般认为是CentOS的iptabls防火墙的问题,方法如下: ps -ef | grep tomcat ker 4399 1 6 21:46 pts/1 00:00:01 /usr/java/jdk ...

  4. Java 基本语法---Java方法

    Java 基本语法---Java方法 0.概述 方法:就是用来解决一类问题的代码的有序组合,是一个功能模块: 在方法部分,只使用对象名词调用方法: Scanner sc = new Scanner(S ...

  5. KnockoutJs学习笔记(八)

    with binding用于创建一个新的绑定环境(binding context),包含with binding的元素的所有子元素都将处于指定的object的环境限定内. 下面是一个简单的使用with ...

  6. 微信小程序开发之IOS/Android兼容坑(持续更新)

    一.时间转换问题: 这不只是小程序上面的问题是ios系统 都有这个问题就是new  Date("2017-06-16") 在IOS会出现NAN的情况所以对于时间转换需要另行封装,解 ...

  7. 使用Golang编写优化算法 (1)

    动手写点东西是学习新知识很重要的一个阶段.之前用 Python 和 JavaScript 实现优化算法,现在用 Golang 来实现.语法上略有不爽,某些C语言的思维又回来了. - Golang 用 ...

  8. Linux系统运维笔记(一),查看系统版本和设置系统时间

    Linux系统运维笔记 查看系统版本和设置系统时间 查看系统版本 lsb_release -a (适用于所有的linux,包括Redhat.SuSE.Debian等发行版,但是在debian下要安装l ...

  9. hadoop日志数据分析开发步骤及代码

    日志数据分析:1.背景1.1 hm论坛日志,数据分为两部分组成,原来是一个大文件,是56GB:以后每天生成一个文件,大约是150-200MB之间:1.2 日志格式是apache common日志格式: ...

  10. Thinkphp分布式数据库连接代码分析

    Thinkphp作为国内的一款流行框架,相信使用的人一定不在少数.本篇我们来分析一下Thinkphp中比较重要的一部分——分布式数据库的连接. 当然了,我们在这里不是去将如何使用模型去对数据库进行增删 ...