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

Community-driven set of best practices for AngularJS application development

License

NotificationsYou must be signed in to change notification settings

birendra-90/angularjs-style-guide

 
 

Repository files navigation

Join the chat at https://gitter.im/mgechev/angularjs-style-guide

Introduction

The goal of this style guide is to present a set of best practices and style guidelines for one AngularJS application.These best practices are collected from:

  1. AngularJS source code
  2. Source code or articles I've read
  3. My own experience

Note 1: this is still a draft of the style guide, its main goal is to be community-driven so filling the gaps will be greatly appreciated by the whole community.

Note 2: before following any of the guidelines in the translations of the English document, make sure they are up-to date. The latest version of the AngularJS style guide is in the current document.

In this style guide you won't find common guidelines for JavaScript development. Such can be found at:

  1. Google's JavaScript style guide
  2. Mozilla's JavaScript style guide
  3. GitHub's JavaScript style guide
  4. Douglas Crockford's JavaScript style guide
  5. Airbnb JavaScript style guide
  6. Idiomatic JavaScript style guide

For AngularJS development recommended is theGoogle's JavaScript style guide.

In AngularJS's GitHub wiki there is a similar section byProLoser, you can check ithere.

Translations

Table of content

General

Directory structure

Since a large AngularJS application has many components it's best to structure it in a directory hierarchy.There are two main approaches:

  • Creating high-level divisions by component types and lower-level divisions by functionality.

In this way the directory structure will look like:

.├── app│   ├── app.js│   ├── controllers│   │   ├── home│   │   │   ├── FirstCtrl.js│   │   │   └── SecondCtrl.js│   │   └── about│   │       └── ThirdCtrl.js│   ├── directives│   │   ├── home│   │   │   └── directive1.js│   │   └── about│   │       ├── directive2.js│   │       └── directive3.js│   ├── filters│   │   ├── home│   │   └── about│   └── services│       ├── CommonService.js│       ├── cache│       │   ├── Cache1.js│       │   └── Cache2.js│       └── models│           ├── Model1.js│           └── Model2.js├── partials├── lib└── test
  • Creating high-level divisions by functionality and lower-level divisions by component types.

Here is its layout:

.├── app│   ├── app.js│   ├── common│   │   ├── controllers│   │   ├── directives│   │   ├── filters│   │   └── services│   ├── home│   │   ├── controllers│   │   │   ├── FirstCtrl.js│   │   │   └── SecondCtrl.js│   │   ├── directives│   │   │   └── directive1.js│   │   ├── filters│   │   │   ├── filter1.js│   │   │   └── filter2.js│   │   └── services│   │       ├── service1.js│   │       └── service2.js│   └── about│       ├── controllers│       │   └── ThirdCtrl.js│       ├── directives│       │   ├── directive2.js│       │   └── directive3.js│       ├── filters│       │   └── filter3.js│       └── services│           └── service3.js├── partials├── lib└── test
  • In case the directory name contains multiple words, use lisp-case syntax:
app ├── app.js └── my-complex-module     ├── controllers     ├── directives     ├── filters     └── services
  • Put all the files associated with the given directive (i.e. templates, CSS/SASS files, JavaScript) in a single folder. If you choose to use this style be consistent and use it everywhere along your project.
app└── directives    ├── directive1    │   ├── directive1.html    │   ├── directive1.js    │   └── directive1.sass    └── directive2        ├── directive2.html        ├── directive2.js        └── directive2.sass

This approach can be combined with both directory structures above.

  • The unit tests for a given component should be located in the directory where the component is. This way when you make changes to a given component finding its test is easy. The tests also act as documentation and show use cases.
services├── cache│   ├── cache1.js│   └── cache1.spec.js└── models    ├── model1.js    └── model1.spec.js
  • Theapp.js file should contain route definitions, configuration and/or manual bootstrap (if required).
  • Each JavaScript file should only holda single component. The file should be named with the component's name.
  • Use AngularJS project structure template likeYeoman,ng-boilerplate.

Conventions about component naming can be found in each component section.

Markup

TLDR; Put the scripts at the bottom.

<!DOCTYPE html><htmllang="en"><head><metacharset="utf-8"><title>MyApp</title></head><body><divng-app="myApp"><divng-view></div></div><scriptsrc="angular.js"></script><scriptsrc="app.js"></script></body></html>

Keep things simple and put AngularJS specific directives after standard attributes. This will make it easier to skim your code and will make it easier to maintain because your attributes are consistently grouped and positioned.

<formclass="frm"ng-submit="login.authenticate()"><div><inputclass="ipt"type="text"placeholder="name"requireng-model="user.name"></div></form>

Other HTML attributes should follow the Code Guide'srecommendation

##Naming conventionsThe following table is shown the naming conventions for every element:

ElementNaming styleExampleusage
ModuleslowerCamelCaseangularApp
ControllersFunctionality + 'Ctrl'AdminCtrl
DirectiveslowerCamelCaseuserInfo
FilterslowerCamelCaseuserFilter
ServicesUpperCamelCaseUserconstructor
FactorieslowerCamelCasedataFactoryothers

Others

  • Use:
    • $timeout instead ofsetTimeout
    • $interval instead ofsetInterval
    • $window instead ofwindow
    • $document instead ofdocument
    • $http instead of$.ajax
    • $location instead ofwindow.location or$window.location
    • $cookies instead ofdocument.cookie

This will make your testing easier and in some cases prevent unexpected behaviour (for example, if you missed$scope.$apply insetTimeout).

  • Automate your workflow using tools like:

  • Use promises ($q) instead of callbacks. It will make your code look more elegant and clean, and save you from callback hell.

  • Use$resource instead of$http when possible. The higher level of abstraction will save you from redundancy.

  • Use an AngularJS pre-minifier (ng-annotate) for preventing problems after minification.

  • Don't use globals. Resolve all dependencies using Dependency Injection, this will prevent bugs and monkey patching when testing.

  • Avoid globals by using Grunt/Gulp to wrap your code in Immediately Invoked Function Expression (IIFE). You can use plugins likegrunt-wrap orgulp-wrap for this purpose. Example (using Gulp)

    gulp.src("./src/*.js").pipe(wrap('(function(){\n"use strict";\n<%= contents %>\n})();')).pipe(gulp.dest("./dist"));
  • Do not pollute your$scope. Only add functions and variables that are being used in the templates.

  • Prefer the usage ofcontrollers instead ofngInit. There are only a few appropriate uses of ngInit, such as for aliasing special properties of ngRepeat, and for injecting data via server side scripting. Besides these few cases, you should use controllers rather than ngInit to initialize values on a scope. The expression passed tongInit should go through lexing, parsing and evaluation by the Angular interpreter implemented inside the$parse service. This leads to:

    • Performance impact, because the interpreter is implemented in JavaScript
    • The caching of the parsed expressions inside the$parse service doesn't make a lot of sense in most cases, sincengInit expressions are often evaluated only once
    • Is error-prone, since you're writing strings inside your templates, there's no syntax highlighting and further support by your editor
    • No run-time errors are thrown
  • Do not use$ prefix for the names of variables, properties and methods. This prefix is reserved for AngularJS usage.

  • Do not useJQUERY inside your app, If you must, useJQLite instead withangular.element.

  • When resolving dependencies through the DI mechanism of AngularJS, sort the dependencies by their type - the built-in AngularJS dependencies should be first, followed by your custom ones:

module.factory('Service',function($rootScope,$timeout,MyCustomDependency1,MyCustomDependency2){return{//Something};});

Modules

  • Modules should be named with lowerCamelCase. For indicating that moduleb is submodule of modulea you can nest them by using namespacing like:a.b.

    There are two common ways for structuring the modules:

    1. By functionality
    2. By component type

    Currently there's not a big difference, but the first way looks cleaner. Also, if lazy-loading modules is implemented (currently not in the AngularJS roadmap), it will improve the app's performance.

Controllers

  • Do not manipulate DOM in your controllers, this will make your controllers harder for testing and will violate theSeparation of Concerns principle. Use directives instead.

  • The naming of the controller is done using the controller's functionality (for example shopping cart, homepage, admin panel) and the substringCtrl in the end.

  • Controllers are plain javascriptconstructors, so they will be named UpperCamelCase (HomePageCtrl,ShoppingCartCtrl,AdminPanelCtrl, etc.).

  • The controllers should not be defined as globals (even though AngularJS allows this, it is a bad practice to pollute the global namespace).

  • Use the following syntax for defining controllers:

    functionMyCtrl(dependency1,dependency2, ...,dependencyn){// ...}module.controller('MyCtrl',MyCtrl);

    In order to prevent problems with minification, you can automatically generate the array definition syntax from the standard one using tools likeng-annotate (and grunt taskgrunt-ng-annotate).

    Another alternative will be to use$inject like:

    angular.module('app').controller('Homepage',Homepage);Homepage.$inject=['$log','$http','ngRoute'];functionHomepage($log,$http,ngRoute){// ...}
  • Avoid use of$scope service to define functions and properties as part of controllers. Use$scope only if It's really needed:0. For publish and subscribe to events:$scope.$emit,$scope.$broadcast, and$scope.$on.0. Forwatch values or collections:$scope.$watch,$scope.$watchCollection

  • Prefer usingcontroller as syntax and capturethis using a variable:

    <divng-controller="MainCtrl as main">   {{ main.things }}</div>
    app.controller('MainCtrl',MainCtrl);MainCtrl.$inject=['$http'];functionMainCtrl($http){varvm=this;//a clearer visual connection on how is defined on the viewvm.title='Some title';vm.description='Some description';$http.get('/api/main/things').success(function(things){vm.things=things;// Adding 'things' as a property of the controller});}

    Avoid usingthis keyword repeatedly inside a controller:

    app.controller('MainCtrl',MainCtrl);MainCtrl.$inject=['$http'];// AvoidfunctionMainCtrl($http){this.title='Some title';this.description='Some description';$http.get('/api/main/things').success(function(things){// Warning! 'this' is in a different context here.// The property will not be added as part of the controller contextthis.things=things;});}

    Using a consistent and short variable name is preferred, for examplevm.

    The main benefits of using this syntax:

    • Creates an 'isolated' component - binded properties are not part of$scope prototype chain. This is good practice since$scope prototype inheritance has some major drawbacks (this is probably the reason it was removed on Angular 2):
      • It is hard to track where data is coming from.
      • Scope's value changes can affect places you did not intend to affect.
      • Harder to refactor.
      • The 'dot rule'.
    • Removes the use of$scope when no need for special operations (as mentioned above). This is a good preparation for AngularJS V2.
    • Syntax is closer to that of a 'vanilla' JavaScript constructor

    Digging more intocontroller as:digging-into-angulars-controller-as-syntax

  • If using array definition syntax, use the original names of the controller's dependencies. This will help you produce more readable code:

    functionMyCtrl(l,h){// ...}module.controller('MyCtrl',['$log','$http',MyCtrl]);

    which is less readable than:

    functionMyCtrl($log,$http){// ...}module.controller('MyCtrl',['$log','$http',MyCtrl]);

    This especially applies to a file that has so much code that you'd need to scroll through. This would possibly cause you to forget which variable is tied to which dependency.

  • Make the controllers as lean as possible. Abstract commonly used functions into a service.

  • Avoid writing business logic inside controllers. Delegate business logic to amodel, using a service.For example:

    //This is a common behaviour (bad example) of using business logic inside a controller.angular.module('Store',[]).controller('OrderCtrl',function(){varvm=this;vm.items=[];vm.addToOrder=function(item){vm.items.push(item);//-->Business logic inside controller};vm.removeFromOrder=function(item){vm.items.splice(vm.items.indexOf(item),1);//-->Business logic inside controller};vm.totalPrice=function(){returnvm.items.reduce(function(memo,item){returnmemo+(item.qty*item.price);//-->Business logic inside controller},0);};});

    When delegating business logic into a 'model' service, controller will look like this (see 'use services as your Model' for service-model implementation):

    //Order is used as a 'model'angular.module('Store',[]).controller('OrderCtrl',function(Order){varvm=this;vm.items=Order.items;vm.addToOrder=function(item){Order.addToOrder(item);};vm.removeFromOrder=function(item){Order.removeFromOrder(item);};vm.totalPrice=function(){returnOrder.total();};});

    Why business logic / app state inside controllers is bad?

    • Controllers instantiated for each view and dies when the view unloads
    • Controllers are not reusable - they are coupled with the view
    • Controllers are not meant to be injected
  • Communicate within different controllers using method invocation (possible when a child wants to communicate with its parent) or$emit,$broadcast and$on methods. The emitted and broadcasted messages should be kept to a minimum.

  • Make a list of all messages which are passed using$emit,$broadcast and manage it carefully because of name collisions and possible bugs.

    Example:

    // app.js/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *Custom events:  - 'authorization-message' - description of the message    - { user, role, action } - data format      - user - a string, which contains the username      - role - an ID of the role the user has      - action - specific action the user tries to perform* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  • When you need to format data encapsulate the formatting logic into afilter and declare it as dependency:

    functionmyFormat(){returnfunction(){// ...};}module.filter('myFormat',myFormat);functionMyCtrl($scope,myFormatFilter){// ...}module.controller('MyCtrl',MyCtrl);
  • In case of nested controllers use "nested scoping" (thecontrollerAs syntax):

    app.js

    module.config(function($routeProvider){$routeProvider.when('/route',{templateUrl:'partials/template.html',controller:'HomeCtrl',controllerAs:'home'});});

    HomeCtrl

    functionHomeCtrl(){varvm=this;vm.bindingValue=42;}

    template.html

    <divng-bind="home.bindingValue"></div>

Directives

  • Name your directives with lowerCamelCase.
  • Usescope instead of$scope in your link function. In the compile, post/pre link functions you have already defined arguments which will be passed when the function is invoked, you won't be able to change them using DI. This style is also used in AngularJS's source code.
  • Use custom prefixes for your directives to prevent name collisions with third-party libraries.
  • Do not useng orui prefixes since they are reserved for AngularJS and AngularJS UI usage.
  • DOM manipulations must be done only through directives.
  • Create an isolated scope when you develop reusable components.
  • Use directives as attributes or elements instead of comments or classes, this will make your code more readable.
  • Usescope.$on('$destroy', fn) for cleaning up. This is especially useful when you're wrapping third-party plugins as directives.
  • Do not forget to use$sce when you should deal with untrusted content.

Filters

  • Name your filters with lowerCamelCase.
  • Make your filters as light as possible. They are called often during the$digest loop so creating a slow filter will slow down your app.
  • Do a single thing in your filters, keep them coherent. More complex manipulations can be achieved by piping existing filters.

Services

This section includes information about the service component in AngularJS. It is not dependent of the way of definition (i.e. as provider,.factory,.service), except if explicitly mentioned.

  • Use camelCase to name your services.

    • UpperCamelCase (PascalCase) for naming your services, used as constructor functions i.e.:

      functionMainCtrl(User){varvm=this;vm.user=newUser('foo',42);}module.controller('MainCtrl',MainCtrl);functionUser(name,age){this.name=name;this.age=age;}module.factory('User',function(){returnUser;});
    • lowerCamelCase for all other services.

  • Encapsulate all the business logic in services. Prefer using it as yourmodel. For example:

    //Order is the 'model'angular.module('Store').factory('Order',function(){varadd=function(item){this.items.push(item);};varremove=function(item){if(this.items.indexOf(item)>-1){this.items.splice(this.items.indexOf(item),1);}};vartotal=function(){returnthis.items.reduce(function(memo,item){returnmemo+(item.qty*item.price);},0);};return{items:[],addToOrder:add,removeFromOrder:remove,totalPrice:total};});

    See 'Avoid writing business logic inside controllers' for an example of a controller consuming this service.

  • Services representing the domain preferably aservice instead of afactory. In this way we can take advantage of the "klassical" inheritance easier:

    functionHuman(){//body}Human.prototype.talk=function(){return"I'm talking";};functionDeveloper(){//body}Developer.prototype=Object.create(Human.prototype);Developer.prototype.code=function(){return"I'm coding";};myModule.service('human',Human);myModule.service('developer',Developer);
  • For session-level cache you can use$cacheFactory. This should be used to cache results from requests or heavy computations.

  • If given service requires configuration define the service as provider and configure it in theconfig callback like:

    angular.module('demo',[]).config(function($provide){$provide.provider('sample',function(){varfoo=42;return{setFoo:function(f){foo=f;},$get:function(){return{foo:foo};}};});});vardemo=angular.module('demo');demo.config(function(sampleProvider){sampleProvider.setFoo(41);});

Templates

  • Useng-bind orng-cloak instead of simple{{ }} to prevent flashing content.
  • Avoid writing complex expressions in the templates.
  • When you need to set thesrc of an image dynamically useng-src instead ofsrc with{{ }} template.
  • When you need to set thehref of an anchor tag dynamically useng-href instead ofhref with{{ }} template.
  • Instead of using scope variable as string and using it withstyle attribute with{{ }}, use the directiveng-style with object-like parameters and scope variables as values:
<divng-controller="MainCtrl as main"><divng-style="main.divStyle">my beautifully styled div which will work in IE</div>;</div>
angular.module('app').controller('MainCtrl',MainCtrl);MainCtrl.$inject=[];functionMainCtrl(){varvm=this;vm.divStyle={width:200,position:'relative'};}

Routing

  • Useresolve to resolve dependencies before the view is shown.
  • Do not place explicit RESTful calls inside theresolve callback. Isolate all the requests inside appropriate services. This way you can enable caching and follow the separation of concerns principle.

i18n

  • For newer versions of the framework (>=1.4.0) use the built-in i18n tools, when using older versions (<1.4.0) useangular-translate.

Performance

  • Optimize the digest cycle

    • Watch only the most vital variables. When required to invoke the$digest loop explicitly (it should happen only in exceptional cases), invoke it only when required (for example: when using real-time communication, don't cause a$digest loop in each received message).
    • For content that is initialized only once and then never changed, use single-time watchers likebindonce for older versions of AngularJS or one-time bindings in AngularJS >=1.3.0.
    • Make the computations in$watch as simple as possible. Making heavy and slow computations in a single$watch will slow down the whole application (the$digest loop is done in a single thread because of the single-threaded nature of JavaScript).
    • When watching collections, do not watch them deeply when not strongly required. Better use$watchCollection, which performs a shallow check for equality of the result of the watched expression and the previous value of the expression's evaluation.
    • Set third parameter in$timeout function to false to skip the$digest loop when no watched variables are impacted by the invocation of the$timeout callback function.
    • When dealing with big collections, which change rarely,use immutable data structures.
  • Consider decreasing number of network requests by bundling/caching html template files into your main javascript file, usinggrunt-html2js /gulp-html2js. Seehere andhere for details. This is particularly useful when the project has a lot of small html templates that can be a part of the main (minified and gzipped) javascript file.

Contribution

Since the goal of this style guide is to be community-driven, contributions are greatly appreciated.For example, you can contribute by extending the Testing section or by translating the style guide to your language.

Contributors

mgechevmorizotterpascalockertchatii2412yanivefraimericguirbal
mgechevmorizotterpascalockertchatii2412yanivefraimericguirbal
agnislavmainyaaray7551LeonardCModoranelfinxxXuefeng-Zhu
agnislavmainyaaray7551LeonardCModoranelfinxxXuefeng-Zhu
SullyPlukaszklisgiacomocusinatosusieyyrubystreamjmblog
SullyPlukaszklisgiacomocusinatosusieyyrubystreamjmblog
cironunesguiltryMertSKaanmingchentornadcavarzan
cironunesguiltryMertSKaanmingchentornadcavarzan
kuzzmicryptojuiceastalkerclbnatodorovapetro
kuzzmicryptojuiceastalkerclbnatodorovapetro
whoanvalgreensmeetbrycedwmkerrdchestgsamokovarov
whoanvalgreensmeetbrycedwmkerrdchestgsamokovarov
grvcoelhoyassirhbargaorobalohermankanjabhishekjesselpalmer
grvcoelhoyassirhbargaorobalohermankanjabhishekjesselpalmer
capajjohnnyghostjordanyeenacyotmariolamacchiamischkl
capajjohnnyghostjordanyeenacyotmariolamacchiamischkl
kirsteinmo-grmortonfoxdreame4nikshulipaolov
kirsteinmo-grmortonfoxdreame4nikshulipaolov
vorktanamobaysahatganchikukaneshinimaimiamiandela-abankole
vorktanamobaysahatganchikukaneshinimaimiamiandela-abankole
thomastutsUrielMirandaVladimirKazandooartgrapswizcoderhaoxin
thomastutsUrielMirandaVladimirKazandooartgrapswizcoderhaoxin
giantrayntaookuzmeig1kuzmeig1
giantrayntaookuzmeig1luixaviles

About

Community-driven set of best practices for AngularJS application development

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp