您的位置:首页 > Web前端 > AngularJS

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

2016-06-17 15:37 627 查看
其实使用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


[/code]

在创建指令时,合适的做法是将相关的文件放到同一目录下(如:模板文件,CSS/SASS文件,JavaScript文件)。如果你在整个项目周期都选择这种组织方式,

app
└──directives
├──directive1
│├──directive1.html
│├──directive1.js
│└──directive1.sass
└──directive2
├──directive2.html
├──directive2.js
└──directive2.sass

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

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

命名约定:

元素命名风格实例用途
ModuleslowerCamelCaseangularApp
ControllersFunctionality+'Ctrl'AdminCtrl
DirectiveslowerCamelCaseuserInfo
FilterslowerCamelCaseuserFilter
ServicesUpperCamelCaseUserconstructor
ServiceslowerCamelCasedataFactoryothers

tips:

使用:

$timeout
替代
setTimeout


$interval
insteadof
setInterval


$window
替代
window


$document
替代
document


$http
替代
$.ajax



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: