<div ng-controller="MainController"> {{ someObj.someProp }} </div> app.controller('MainController',function ($scope) { $scope.someObj = { someProp: 'Some value.' }; });
使用Controller as后,变成了
<div ng-controller="MainController as main"> {{ main.someProp }} </div> app.controller('MainController',function ($scope) { this.someProp = 'Some value.' });
更多的参考:
https://github.com/johnpapa/angular-styleguide 其列举了angularjs的各种推荐写法
https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md
更有意义的是,它还可以避免scope的继承,书写更清晰,例如:
子controller可以同步修改父controller的对象,而免去scope继承的问题
<div ng-controller="ParentController as parent"> ParentController: <input type="text" ng-model="parent.foo" /> parent.foo: {{ parent.foo }} <div ng-controller="ChildController as child"> ChildController: <input type="text" ng-model="parent.foo" /> parent.foo: {{ parent.foo }} </div> </div> app.controller('ParentController', function($scope) { this.foo = "bar"; }); app.controller('ChildController',function ($scope) { });
更多参考:
http://www.tuicool.com/articles/Mfeimu