Angularjs 1.2.0 版本开始Controller有一个很友好的更新 "Controller as object",这一用法能很好的避免scope嵌套使用时带来的继承问题。
1.
angular.module('app').controller('parentController',[function(){
this.title="parent title"
}]);
<div ng-controller="parentController as parent">
{{parent.title}}
</div>
2.
angular.module('app').controller('parentController',[function(){
this.title="parent title"
}]);
angular.module('app').controller('childController',[function(){
this.title="child title"
}]);
<div ng-controller="parentController as parent">
<span style="white-space:pre"> </span>{{parent.title}}
<span style="white-space:pre"> </span><div ng-controller="childController as child">
<span style="white-space:pre"> </span>{{child.title}}
<span style="white-space:pre"> </span></div>
</div>
3.$routeProvider 也支持Controller as 用法,第三方的ui-router同样也支持。
$routeProvider
.when('/', {
templateUrl: 'views.html',
controllerAs: 'parent',
controller: 'parentController'
});
<pre name="code" class="javascript">$stateProvider
.state('example', {
url: 'example',
views: {
"main": {
templateUrl: 'example.html',
<span style="white-space:pre"> </span>controller:'parentController as parent'
}
}
});