Using ES6 in Angularjs

Source: Internet
Author: User

This article records some of the angularjs used in combination with ES6.

Export import of module in ES6

class Maincontroller {    Constructor (searchservice) {        this. Searchservice=  Searchservice;    }        Search () {        this.searchservice            . Fetch (this. searchterm)            = =                {this. Items = resposne.data.items;}}    }} Export {Maincontroller}

How do I register the controller in module with the module?

Import {Maincontroller} from './maincontroller './seachservice '; angualr    . Module (' app ', [ ])    . Controller (' Maincontroller ', Maincontroller)    . Service (' Searchservice ', searchservice);

Inheritance in the ES6

class pagecontroller{    Constructor (name) {        this. Name= name;    }        SayHello () {        returnthis. Name;    }} Export {Pagecontroller}


In a different file:

Import {Pagecontroller} from './pagecontroller '; class Productpagecontroller extends Pagecontroller {    Constructor () {        super (' Jack ');}    } Export {Productpagecontroller}

Finally, register to the module to:

angular    . Module (' app ', [])    . Controller (' Productpagecontroller ', Productpagecontroller) ;

The wording of service and controller in ES6

class userservice{    Constructor ($http) {        this. $http= $http;    }        Getfullname () {        returnthis. $http. Get (' api/user/details ');}    } Class mycontroller{    // Note: When defining the class name is UserService, the true name is in service (' Realname ', Userservie      Constructor (userservice)        {this. userName = result.fullname) defined in the.    }} Angular.module(' app ')    . Service (' UserService ', UserService)    . Controller (' Mycontroller ', Mycontroller);

The writing of providers in ES6

class myprovider{    constructor () {        this. Apipath = ' Default/api';    }    Setapipath (value) {        this. Apipath= value;    }    $get ($http) {        return  {            = = $http. Get(this. apipath);}}}    

The injected provider in the ES6 is written in $get () and cannot be injected into the constructor. There must be a $get () method in the provider.


The writing of factory in ES6

class thing{    constructor () {        console.log (' Create the Thing ');        ShowMsg ();    }    ShowMsg () {        console.log (' some msg ');}    } Class thingfactory{    Constructor ($timeout) {        this. $timeout= $timeout;    }        Creatething () {        returnthisnew Thing (), +);}    }

How do I register with the module?


The first form of a notation

Angular.module (' app ')    . Factory (new thingfactory ());

The above is wrong, because $timeout has not yet been injected. Can write like this.

Angular.module (' app ')    . Factory (new thingfactory ($timeout)]);

The second type of notation

However, the above wording is not the most ideal. It is best to write in the class.

class thingfactory{    Constructor ($timeout) {        this. $timeout= $timeout;    }        Creatething () {        returnthisnew Thing (), +);     = [' $timeout '];

And then

Angular.module (' app ')    . Factory (new thingfactory ());


The third kind of wording

class thingfactory{Constructor ($timeout) { This. $timeout =$timeout; } creatething () {return  This. $timeout (() =NewThing (), 1000); }}thingfactory. $inject= [' $timeout '];varCONSTRUCTORFN =thingfactory;//args = [' $timeout ']varargs =constructorfn. $inject;//Create Thingfactory instances based on parameters, any number of parametersvarFactoryfunction = (.... args) = {    return Newconstructorfn (.... args);}//[' $timeout ', ($timeout) = new Thingfactory ($timeout)]varFactoryarray =Args.push (factoryfunction); Angular.module (' App '). Factory (' Thingfactory ', factoryarray);

The writing of directive in ES6

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 () *) + ' px '); Element.css (' Top ', (Math.random () *) + ' px '); }}

Above, if both the compile and link methods are used, the link method should be the return value of the compile.

Compile (telement) {    telement.css (' position ', ' absolute ');     return  This . Link;}

Above, when angular calls the This.link method, this is not called in the current context of mydirective. $interval (() = This.move (Element), 1000); The undefined type error is reported.

If you change to this:

Compile (telement) {    telement.css (' position ', ' absolute ');     return (scope, Element) = {        this. Move (element), +);}     

Here, when you use the + =, call this. $interval (() = This.move (Element), 1000), and the method guarantees that the current context in which the mydirective is located is also available.

You can also write this:

Compile (telement) {    telement.css (' position ', ' absolute ');     return this. Link.bind (this);} Link (scope, element) {    this. Move (element), +);} 

However, all of the above practices must call the compile method, and in a real-world scenario, calling the compile method is not required. It is best to write:

varCONSTRUCTORFN =mydirective;//is there a compile methodif(!constructorFn.prototype.compile) {//if not, create a compile method from the prototypeConstructorFn.prototype.compile = () = {};}varOriginalcompilefn =_clonefunction (constructorFn.prototype.compile);//overriding the Compile method_override (Constructorfn.prototype, ' compile ',function () {    return function () {            //first call the original compile methodOriginalcompilefn.apply ( This, arguments); //if directive contains the link method and then executes the link method, bind the correct context        if(constructorFn.prototype.link) {returnConstructorFn.prototype.link.bind ( This); }    };});

How to register controller, factory, provider, etc. with module

Michael Bromley also specializes in writing a Help method here.

This is generally used:

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);

Resources:
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

Using ES6 in Angularjs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.