AngularJs 代码风格指南
这篇文章(5632e0496fec47d05396a864)是从 Teambition 迁移过来的
Controller 的别名
使用这种风格编写代码,可以增强可读性,便于维护及减少出错的可能
app.js
(function(global) {
'use strict';
var __appname = 'myApp'
angular.module(__appname, ['myModule'])
.config(__config)
.run(__run);
function __config($somethingInject) {
// ...
}
__config.$inject = ['$somethingInject'];
function __run($somethingInject){
//...
}
__run.$inject = ['$somethingInject']
// 启动 App
angular.element(document).ready(function() {
// { strictDi:true} 为可选参数
// 在 AngularJs 1.3 版本以后,使用静态注入(strictDi)可以提高性能
angular.bootstrap(document, [__appname],{ strictDi:true});
});
})();
myModule.js
(function(global) {
'use strict';
angular.module('myModule', ['subModule'])
.controller('MainCtrl', MainCtrl);
function MainCtrl($somethingInject) {
// 重命名 this
// 这一步是为了后续代码中对this的错误引用;
var mc = this;
mc.username = 'Tom';
// ...
}
MainCtrl.$inject = ['$somethingInject'];
})();
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
...
<title>myApp demo</title>
</head>
<!-- 使用 as 指定别名-->
<body ng-controller="MainCtrl as mc">
Hello {{mc.username}}!
...
<script src='myModule.js'></script>
<script src='app.js'></script>
</body>
</html>