1. 把控制器中与视图无关的逻辑都移到"服务(service)"中
2. 新手常犯错误
$routeProvider.when('/workout', {
templateUrl: 'partials/workout.html',
controller: 'WorkoutController'
});
3. 本质上,当写 directive 时令时。当我们设置了 link 参数,实际上是创建了一个 postLink() 链接函数,以便 compile() 函数可以定义链接函数。编译函数(compile)负责对模板DOM进行转换。 链接函数(link) 负责将作用域和 DOM 进行链接。
....
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
},
link: function postLink(scope, iElement, iAttrs) { ... }
...
个人理解compile函数的功能更强。
详情内容:[译]ng指令中的compile与link函数解析
4. 使用ng-repeat指令,为防止重复值发生的错误。加上track by $index。
<li ng-repeat="i in ctrl.list track by $index">{{ i }}</li>
5. 关于向父子controller中传递内容。
- `$emit` 只能向parent controller传递event与data
- `$broadcast` 只能向child controller传递event与data
- `$on` 用于接收event与data
6. 尽量要少操作DOM.这里有个简单的例子, 我们要做一个切换的按钮 (这个例子有点做作和有点长, 主要是为了表示一下很复杂的情况也是这样解决的.)
.directive( 'myDirective', function () {
return {
template: '<a class="btn">Toggle me!</a>',
link: function ( scope, element, attrs ) {
var on = false;
$(element).click( function () {
if ( on ) {
$(element).removeClass( 'active' );
}
else {
$(element).addClass( 'active' );
}
on = !on;
});
}
};
});
这个例子中有些错误, 第一,jQuery是不需要的. 第二即使其他地方引入了jQuery,我们还是可以用 angular.element 来替换. 第三, 即使要使用jQuery, jqLite (angular.element) 也会在引入jQuery时优先使用jQuery. 所以不要用$,而是angular.element. 第四, jqLite 不需要包裹$, 在link函数中,element 已经是一个jQuery元素被传了进去. 第五,之前说过,模板中与逻辑混在一起。
改进后
.directive( 'myDirective2', function () {
return {
scope: true,
template: '<a class="btn" ng-class="{active: on}" ng-click="toggle()">Toggle me!</a>',
link: function ( scope, element, attrs ) {
scope.on = false;
scope.toggle = function () {
scope.on = !scope.on;
};
}
};
});
7. ng默认的解析标签是{{}},有时候会和其他模板引擎中的标签冲突,如Symfony的twig的模板。如要修改
var app = angular.module('myApp', []);
app.config(['$interpolateProvider', function($interpolateProvider) {
$interpolateProvider.startSymbol('{[');
$interpolateProvider.endSymbol(']}');
}]);
8. 重置form到初始状态,并清除之前的错误信息
// form.$setPristine()可以重置表单到dirty之前的状态,并且清除form上的ng-dirty类名
// accountForm是form元素的name属性值
$scope.accountForm.$setPristine();
$scope.accountForm.$setUntouched();
9. 使用一次性绑定提高性能。尤其是在ng-repeat中
<p>Hello {{::name}}!</p>
<custom-directive two-way-attribute="::oneWayExpression"></custom-directive>