Angular 笔记系列,一项目组织与命名规范

其实使用 Angular.js 做项目已经很久了,也遇到过许多问题。其中很多问题的出现都是因为没有按照规范或者最佳实践来做,大部分原因是学的不够细,很多 tips 没 get 到,用到项目中就会出现各种问题,我遇到的问题最多的就是 directive 这块。很多的 bug都是指令的嵌套引发的。当时自己学的时候很多小 tip 也没有注意过,打算重新撸一遍文档,夯实一下基础。


Angular 的项目结构,常见的有两种方式:

一丶 类型优先,业务功能其次,当前我们项目就采用的是这种方式:

├── 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

二丶业务功能优先,类型其次:

.
├── 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



命名规范:


  • 当目录里有多个单词时, 使用 lisp-case 语法,项目中的变量一般会采用驼峰命名法:
app
 ├── app.js
 └── my-complex-module
     ├── controllers
     ├── directives
     ├── filters
     └── services
  • 在创建指令时,合适的做法是将相关的文件放到同一目录下 (如:模板文件, CSS/SASS 文件, JavaScript文件)。如果你在整个项目周期都选择这种组织方式,
app
└── directives
    ├── directive1
    │   ├── directive1.html
    │   ├── directive1.js
    │   └── directive1.sass
    └── directive2
        ├── directive2.html
        ├── directive2.js
        └── directive2.sass
标记:

保持标签的简洁并把AngularJS的标签放在标准HTML属性后面。这样提高了代码可读性。标准HTML属性和AngularJS的属性没有混到一起,提高了代码的可维护性。

<form class="frm" ng-submit="login.authenticate()">
  <div>
    <input class="ipt" type="text" placeholder="name" require ng-model="user.name">
  </div>
</form>
命名约定:
元素命名风格实例用途
ModuleslowerCamelCaseangularApp
ControllersFunctionality + 'Ctrl'AdminCtrl
DirectiveslowerCamelCaseuserInfo
FilterslowerCamelCaseuserFilter
ServicesUpperCamelCaseUserconstructor
ServiceslowerCamelCasedataFactoryothers

tips:

  • 使用:
    • $timeout 替代 setTimeout
    • $interval instead of setInterval
    • $window 替代 window
    • $document 替代 document
    • $http 替代 $.ajax