Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A collection of utilities and annotations that make it easier to write Angular 2 style code in AngularJS 1.x

NotificationsYou must be signed in to change notification settings

MikeRyanDev/angular-decorators

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

Looking for the 0.1x docs?

Modules

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

Module Dependencies

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

Decorators

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.

Inject

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

Component

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'}
Binding Element Attributes to the Controller

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{ ...}
RenamingcontrollerAs

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'})
Changing Scope

By default, components create new, isolate scopes but this can be manually set in the component config object:

@Component({selector:'my-component',scope:false})
Setting the Template

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{ ...}
Requiring Other Directives

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

Transclusion

Use the@Transclude decorator to setup transclusion for your component:

import{Component,Transclude}from'angular-decorators';@Component({selector:'my-component'})@TranscludeclassMyComponent{ ...}

Directive

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(){}}

Filter

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.

Service

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

Factory

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

Providers

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

Animation

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

Extending angular-decorators

Adding Your Own Providers

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.

Extending the Directive Parser

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

Stars

Watchers

Forks

Packages

No packages published

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp