- Notifications
You must be signed in to change notification settings - Fork7
MikeRyanDev/angular-decorators
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
angular-decorators is a library of ES7 decorators for writing Angular 2 style code in AngularJS.
Notice: While angular-decorators is stable and ready for production, it will not be receiving new feature development. In the future, this project will be deprecated in favor of the community fork of angular-decorators calledng-forward. For more information on the ng-forward project, checkoutthis talk by Pete Bacon Darwin.
Installation via npm
npm install angular-decorators --save
Installation via jspm
jspm install angular-decorators
The standardangular.module does not understand the metadata attached to your classes from this library's decorators. Use the provided Module function to create decorator-friendly Angular modules:
import{Module}from'angular-decorators';// Create a new module:letmyModule=Module('my-module',['ui.bootrap','ui.router']);// Reference a pre-existing module:letotherModule=Module('my-module');
All decorated classes are added to the module usingadd:
import{Service,Module}from'angular-decorators';@Service('MyService')classMyService{}Module('my-module',[]).add(MyService);
If you need the rawangular.module, use thepublish function:
letangularModule=myModule.add(AnnotatedClass).publish();
Modules aliasconfig andrun blocks to the internalangular-module:
Module('example',[]).config(...).run(...);
You do not need to publish a module to add it as a dependency to another module:
letmyModule=Module('my-module',[]);letotherModule=Module('other-module',[myModule]);
This works for vanilla AngularJS modules as well:
letotherModule=angular.module('other-module',[]);letmyModule=Module('my-module',[otherModule]);letlastModule=angular.module('last-module',[myModule.name]);
The decorators provided in this package followthis proposal. They work by adding metadata to your classes under the$ng-decs namespace using thereflect-metadata polyfill.
The@Inject decorator lets you specify dependencies:
@Inject('$q','$http')classMyService{constructor($q,$http){}}
When inheriting from a decorated class, child dependencies are specified before parent dependencies letting you capture parent dependencies using a rest parameter:
@Inject('$q','$http')classParent{constructor($q,$http){}}@Inject('$timeout')classChildextendsParent{constructor($timeout, ...parentDependencies){super(...parentDependencies);}}
The@Component decorator lets you create components in AngularJS by wrapping the directive API and setting you up with sensible defaults:
import{Component,Inject,Module}from'angular-decorators';@Component({selector :'my-component'})@Inject('$q')classMyComponentCtrl{constructor($q){ ...}}exportdefaultModule('my-component-module',[]).add(MyComponentCtrl);
The directive definition object generated for the above component is:
{controller:['$q',MyComponentCtrl],controllerAs:'myComponent',bindToController:true,scope:{},restrict:'E'}
Supply an array of properties key of your config object using Angular 2 property syntax:
@Component({selector:'my-component',properties:['myProp: =renamedProp','@anotherAttribute']})classMyComponentCtrl
This becomes:
.directive('myComponent',function(){return{restrict:'E',controller:functionMyComponentCtrl{},controllerAs:'myComponent',scope:{},bindToController:{'myProp' :'=renamedProp','anotherAttribute' :'@'}}})
For information on attribute binding, view theAngularJS docs on scopes.
Note: the above uses the newbindToController syntax introduced in AngularJS 1.4. For AngularJS 1.3, usebind in your@Component config instead ofproperties:
import{Component}from'angular-decorators';@Component({selector:'my-component',bind:{myProp:'=renamedProp',anotherAttribute:'@'}})classMyComponentCtrl{ ...}
By default, thecontrollerAs property is a camelCased version of your selector (i.e.my-own-component'scontrollerAs would bemyOwnComponent'). You can override this by specifying a new name in the@Component config object:
@Component({selector:'my-component',controllerAs:'vm'})
By default, components create new, isolate scopes but this can be manually set in the component config object:
@Component({selector:'my-component',scope:false})
Templates are added with the@View decorator. Pass in a config object with either an inlinetemplate or atemplateUrl:
import{Component,View}from'angular-decorators';@Component({selector:'my-component'})@View({template:`<h1>My Component Template</h1>`})classMyComponentCtrl{ ...}@Component({selector:'another-component'})@View({templateUrl:'/path/to/template.html'})classAnotherComponentCtrl{ ...}
Use the@Require decorator to require directive controllers and access them using the static link function:
import{Component,Require}from'angular-decorators';@Component({selector :'my-component'})@Require('^parent','myComponent')classMyComponent{staticlink(scope,element,attrs,controllers){let[parent,self]=controllers;self.parent=parent;}}
Use the@Transclude decorator to setup transclusion for your component:
import{Component,Transclude}from'angular-decorators';@Component({selector:'my-component'})@TranscludeclassMyComponent{ ...}
Unlike@Component,@Directive does not create a new isolate scope by default nor does it expose your directive's controller on the scope. It can only be used for directives that you want to restrict to a class name or attribute:
import{Directive}from'angular-decorators';@Directive({selector:'[my-attr]'})classMyAttrCtrl{constructor(){}}@Directive({selector:'.my-class'})classMyClassCtrl{constructor(){}}
The@Filter decorator lets you write class-based filters similar to Angular 2's Pipes:
import{Filter,Module}from'angular-decorators';@Filter('trim')classTrimFilter{// Implementing a supports function is encouraged but optionalsupports(input){return(typeofinput==='string');}transform(input,param){returninput.trim();}}exportdefaultModule('trim-filter',[]).add(TrimFilter);
Thesupports function is an optional test against the input. If thesupports function returns false the generated filter will throw an error instead of applying the transform.
The@Service decorator turns your class into a service:
import{Service,Inject,Module}from'angular-decorators';@Service('MyService')@Inject('$q')classMyService{constructor($q){this.$q=$q;}}exportdefaultModule('my-service',[]).add(MyService);
The@Factory decorator is a complex decorator that assumes you have a class that requires more parameters on instantiation than what will be provided by AngularJS's injector. For example, if you had a class that looked like this:
@Inject('$http')classPost{constructor($http,title,content){}}
and you wanted to make a factory that created a newPost with a parameters for title and content, you would use@Factory:
import{Factory,Inject,Module}from'angular-decorators';@Factory('PostFactory')@Inject('$http')classPost{constructor($http,title,content){}}exportdefaultModule('post-factory',[]).add(Post);
When injected elsewhere use the factory like this:
import{Inject,Service,Module}from'angular-decorators';importPostFactoryfrom'./post-factory';@Service('SomeService')@Inject('PostFactory')classSomeService{constructor(PostFactory){letpost=PostFactory('Title','Some content');}}exportdefaultModule('some-service',[PostFactory]).add(SomeService);
You can override the default factory function by implementing a static create function:
import{Factory,Inject,Module}from'angular-decorators';@Factory('CommentFactory')@Inject('$http','$q')classComment{constructor($http,$q,postID,comment){}staticcreate(dependencies,post,comment){returnnewComment(...dependencies,post.id,comment);}}exportdefaultModule('comment-factory',[]).add(Comment);
Create raw providers using the@Provider decorator. For easily injecting dependencies to the$get function, enable ES7 property initializers in your compiler:
import{Provider,Module}from'angular-decorators';@Provider('SomeService')classSomeServiceProvider{constructor(){this.greeting='hello';}setGreeting(newGreeting){this.greeting=newGreeting;}$get=['$timeout',$timeout=>name=>$timeout(()=>console.log(`${this.greeting}${name}`))];}exportdefaultModule('some-service-provider',[]).add(SomeServiceProvider);
Create animations using the@Animation decorator. RequiresngAnimate to be included in your module:
import{Animation,Inject,Module}from'angular-decorators';importngAnimatefrom'angular-animate';@Animation('.animation-class')@Inject('$q')classMyAnimation{constructor($q){this.$q=$q;}enter(element){returnthis.$q((resolve,reject)=>{ ...});}}exportdefaultModule('my-animation',[ngAnimate]).add(MyAnimation);
You can register your own providers usingModule.addProvider. For instance, if you want to add a new decorator called@RouteableComponent that hooked up a component to the upcoming router, you would start by creating a decorator that set a provider name and type on a class:
import{providerWriter}from'angular-decorators/writers';exportdefaultconstRouteableComponent=name=>targetClass=>{providerWriter.set('type','routeable-component',targetClass);providerWriter.set('name',name,targetClass);}
Then you'll need to register your custom parser:
importModulefrom'angular-decorators/module';Module.addProvider('routeable-component',(provider,name,injectables,ngModule)=>{// implement parsing logic here, adding necessary config/directives/etc to the raw ngModule});
Your parser will be called each time a provider is added to aModule that has the provider type you've specified.
The directive definiton object is derived from all key/value pairs set with thecomponentWriter. Here is an example of creating a priority decorator that sets a directive's priority:
import{componentWriter}from'angular-decorators/writers';exportconstPriority=level=>target=>componentWriter.set('priority',level,target);
No other configuration is required. Simply using@Priority in tandem with@Component or@Directive will work.
About
A collection of utilities and annotations that make it easier to write Angular 2 style code in AngularJS 1.x
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors3
Uh oh!
There was an error while loading.Please reload this page.