LoginSignup
17
17

More than 5 years have passed since last update.

AngularJSのControllerAs記法

Last updated at Posted at 2014-08-20

ControllerAs記法

1.2系からng-controllerでHogeCtrl as hogeという記法が使えるようになっています

<div ng-controller="SomeCtrl as some">
  <p ng-bind="some.name"></p>
</div>
angular.module('app').controller('SomeCtrl', function(){
  var vm = this;
  vm.name = "Ishikari gawa";
});
Ishikari gawa

classライクに書くことが出来ます

nested controller

controllerがネストされた構造のとき、親のscopeを書き換えるには$parentで直接親スコープにアクセスするか、scope.obj.nameのように中間オブジェクトobjを挟み、jsのprototype chain経由で書き換えるかを迫られます。が、ControllerAs記法だとシンプルに書けます。

<div ng-controller="GrandpaController as granpa">
  <p ng-bind="granpa.name"></p>
  <div ng-controller="ParentController as parent">
    <div ng-controller="ChildController as child">
      <p ng-bind="granpa.name"></p>
      <input type="text" ng-model="granpa.name">
    </div>
  </div>
</div>

スクリーンショット 2014-08-20 7.03.27 PM.png

たとえParentとGrandpaの入れ子が逆転しても問題なくなります。

$scopeが必要な時

\$scopeが使えなくなるわけではありません。\$broadcast, \$emit, \$onを使いたい時は$scopeをDIすれば普通に使えます

angular.module('app').controller('SomeCtrl', function($scope){
  var vm = this;
  vm.name = "Ishikari gawa";
  $scope.$on('SomeCoolEvent', function(event, data) {
    // some cool process...
  });
});

\$watchはちょっと工夫が必要。第一引数でwatch対象を返すfunctionを指定します

angular.module('app').controller('SomeCtrl', function($scope){
  var vm = this;
  vm.name = "Ishikari gawa";
  $scope.$watch(function(){
    return vm.name
  }, function(newVal, oldVal) {
    // do some thing
  });
});

Directiveやrouterでの指定

\$routeProviderやdirectiveではcontrollerに加えてcontrollerAsを指定することが出来ます。

// when you use ng-route
$routeProvider.when('/map', { controller: 'MapCtrl', controllerAs: 'map', templateUrl: 'map/index.html' })

ただし、ui-routerにはその記法は無いらしく、controllerでHogeCtrl as hogeのように指定します。

// when you use ui-router
$stateProvider.state('map.home', { url: '/map', controller: 'MapCtrl as map', templateUrl: 'map/index.html' })

まとめ

すごく便利。これをデフォにして欲しいくらいです

参考

17
17
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
17