LoginSignup
5
5

More than 5 years have passed since last update.

AngularJSのControllerの書き方

Last updated at Posted at 2013-05-03

追記

kawaz氏からController含めたDIについて詳細な情報を提示していただいた。ありがとうございます。

とはいえ、この辺のことがあまり前面に出して書かれていないあたり、他のコードを読むときにびっくりしちゃうだろうなぁと思う。


AngularJS公式とかで提示されているサンプルなどを見てみると、大体こんな感じで関数を定義しているところが多い。

function HogeCtrl($scope) {
    // 中身は中略
}


なのでこれまではそれにしたがって書いていたのだけど、githubなどでAngularJSのモジュール等を見るとこういう書き方をしているものを見つけた。

angular.controller('Ctrl', ['$scope', function($scope) {
    // 中略
}]);


AngularJS公式のドキュメントをほじくり返してみると、Understanding the Controller Componentで該当の記述を発見。

NOTE: Many of the examples in the documentation show the creation of functions in the global scope. This is only for demonstration purposes - in a real application you should use the .controller method of your Angular module for your application as follows:

var myApp = angular.module('myApp',[]);

myApp.controller('GreetingCtrl', ['$scope', function($scope) { $scope.greeting = 'Hola!'; }]);

Note also that we use the array notation to explicitly specify the dependency of the controller on the $scope service provided by Angular.

ドキュメント内ではグローバルで関数定義する例が頻出しているけどデモンストレーションだから、開発時にはcontrollerメソッドを使いなさいとのこと。

AngularJSのドキュメントを眺めていると、各ページにコメント欄がついて、ところどころ「サンプルが動かねーよ!」みたいなことが書かれていているのが若干気になるよのね。きちんとメンテされていないのだろうか?

5
5
1

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
5
5