AngularJS 'Controller As'用法
AngularJS 1.2版本中提供了Controller As语法,简单说就是可以在Controller中使用this来替代$scope,使得Controller更像一个传统的JS类,相对于$scope的继承树要理解上要简单一些。
基础用法
传统的Controller是这样写的:
app.controller('MainCtrl', function($scope) {
$scope.title = 'Some title';
});
这种写法下,$scope是注入到MainCtrl中的服务,是Dom元素和Controller之间的粘合剂。
<div ng-controller="MainCtrl">
{ { title } }
</div>
这个孤单的title常常让初学者疑惑。
在AngularJS 1.2版本之后,我们可以这样写:
app.controller('MainCtrl', function() {
this.title = 'Some title';
});
这种写法下,MainCtrl更像是一个JS类:
var MainCtrl = function() {
this.title = 'Some title';
};
var main = new MainCtrl();
在页面上使用时就可以使用Controller As语法,实例化对象
<div ng-controller="MainCtrl as main">
{ { main.title } }
</div>
嵌套块
这种理解上的好处在嵌套块中更加明显:
<div ng-controller="MainCtrl">
{ { title } }
<div ng-controller="AnotherCtrl">
{ { title } }
<div ng-controller="YetAnotherCtrl">
{ { title } }
</div>
</div>
</div>
这个title可能是$scope继承树上的任意一个。而使用Controller as之后:
<div ng-controller="MainCtrl as main">
{ { main.title } }
<div ng-controller="AnotherCtrl as another">
Scope title: { { another.title } }
Parent title: { { main.title } }
<div ng-controller="YetAnotherCtrl as yet">
Scope title: { { yet.title } }
Parent title: { { another.title } }
Parent parent title: { { main.title } }
</div>
</div>
</div>
这就清晰很多。
Directive用法
在Directive中,我们可以这样使用:
app.directive('myDirective', function() {
return {
restrict: 'EA',
template: '<div>{ { my.title } }</div>',
controller: function() {
this.title = 'Some title';
},
controllerAs: 'my'
};
});
$watch
只是$watch还是需要注入$scope:
app.controller('MainCtrl', function($scope) {
this.title = 'Some title';
$scope.$watch(angular.bind(this, function() {
return this.title;
}), function(newVal, oldVal) {});
});
本文地址:http://corncandy.github.io/2014/06/06/angularjs-controller-as/