LoginSignup
1
2

More than 5 years have passed since last update.

Angular.jsのcontrollerをBabel使ってclass記法にすると"Controller not a function, got undefined"と怒られた件

Last updated at Posted at 2015-05-23

controllerをクラス化すると "Controller not a function got undefined"が出た

個人的なものなのかは知りませんが、今までcontrollerは次のように書いていました。

controller.js
//moduleへcontrollerを登録した後でその中身をfunctionに分離して記述、
angular.module('myApp', [])
    .controller('FirstCtrl', FirstCtrl)

function FirstCtrl(){...}

それを単純にES6のクラス記法に直したのが↓ エラーが出ます。

controller.js
// 単純にクラスに直したもの。"Controller not a function, got undefined"と言われるorz
angular.module('myApp', [])
    .controller('FirstCtrl', FirstCtrl)

class FirstCtrl{
    constructor(){...}
    ....
}

このエラーが出るのは単純な理由で、Babelでコンパイルした後のソースは↓のようになってるから。

controller.js(Babelでコンパイル後)
angular.module('myApp', [])
    .controller('FirstCtrl', FirstCtrl)

// FirstCtrlは変数として宣言されてる
var FirstCtrl = function FirstCtrl() {
    _classCallCheck(this, FirstCtrl);
};

".controller('FirstCtrl', FirstCtrl)"で使われるとき、(Hoistingのせいで)変数FirstCtrlは存在してるけど、この時点では”undefined”だから、"not a function"と怒られるのも当然!

だからclassの宣言は、controllerの宣言より上に書かないといけない

controller.js
// ちゃんとうごくやーつ
class FirstCtrl{
    constructor(){...}
    ....
}
angular.module('myApp', [])
    .controller('FirstCtrl', FirstCtrl)

これで小一時間くらい悩んでた orz
こういう初心者ぽいミスはあんまりしたくないなあ

1
2
0

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
1
2