AngularJSでUI-router(routeProvider)を使うとcontrollerが複数回呼ばれる
AngularJSでUI-routerとディレクティブを使って実装しているとき、
controllerが複数回呼ばれてしまう問題が発生し、
その原因が分かったのでメモ&シェア。
※気づいてしまえば簡単な問題でしたが。。
結論から言うと、
"UI-routerでのRouting部分とディレクティブの定義部分で両方でControllerを使うと、
それぞれで呼び出されてしまう"
でした。
いろいろな人が書いているサンプルコードを見ると、
UI-routerでのRouting部分にcontrollerの定義を書いていたため、
UI-router(もしくはrouteProvider)を使う際は必ず書かないといけないのだろう、
と思っていたのが間違いでした。
UI-routerを使っても、静的なページなどでcontrollerを使わないページであれば、
UI-routerのRoutingをする部分に書く必要はないようです。
※逆に書いてしまうと、2回呼び出されます。
僕の場合、UI-router (routeProviderでも同じ)を使って、下記のように実装していました。
※下記、Routing部分とcategory-directive.htmlで
それぞれControllerを呼び出しているのが問題。
Javascript
Routing部分
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider. state('/', { state('category',{ url: '/category', templateUrl: 'view/category.html', controller: 'categoryController' });
Controller
myApp.controller('categoryController', [$scope, function($scope){ console.log("categoryController"); }]);
HTML
ディレクティブ呼び出し部分 (category.html)
<div> <div class="col-xs-8"> <div category-directive></div> </div> <div class="col-xs-4"> <div xxxxx></div> <div yyyyyy></div> </div> </div>
ディレクティブの中身
category-directive.html
<div> <div class="col-xs-8"> <div ng-controller="categoryController">xxxxx</div> </div> <div class="col-xs-4"> <div xxxx></div> <div yyyy></div> </div> </div>
僕の場合は、Controolerはcategory-directive.htmlで呼び出すので、
UI-routerのRoutingをしている部分(この記事であれば、上の方の赤文字)
のcontrollerの定義を消すことにより解決しました。
何か、まだまだAngularJSの本質を理解できてない感です。
AngularJS自体のソースコード読めばいいんでしょうが、なかなか時間もとれず。。。