はじめに
Angular2.0を見据えて1.5から追加された、Component Routerを使ってみます。
2.0と結構違うようなので、1.5で書くことはもうあまり無いかもしれませんが、自分の為に残しておこうと思います。
インストール
bowerを使用すると、これしか見当たりませんでした。。。他にもあるのかもしれません。
https://libraries.io/bower/angular-component-router
bower install angular-component-router --save
モジュールを定義
ngComponentRouter
をmoduleに追加。
var app = angular.module('app', [
'ngComponentRouter'
]);
使い方
トップレベルのコンポーネントを指定する
ルーティングの一番親になるコンポーネントを定義します。
特にない場合は定義不要かもしれません。
app.value('$routerRootComponent', 'rootComponent');
ルーティングを設定
app.component('rootComponent', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [{
path: '/home',
name: 'Home',
component: 'home',
useAsDefault:true
},{
path: '/other',
name: 'Other',
component: 'other',
$canActivate:function(){return true;}
}]
});
ng-outlet
ルーティングで設定したコンポーネントは、<ng-outlet>
に反映される。
ui-routerでいう<ui-view>
のようなものだとおもう。
$routeConfig
path
URLに反映されるpathの名前
component
指定したRouteに対応するComponent
name
リンク先で指定する値。先頭の文字は大文字にするのがルール。
<a ng-link="['Home']">
のように使用する
useAsDefault
useAsDefault:true
を設定した場合、
http://fugaguga/
にアクセスした場合に、http://fugaguga//home
移動するようになる。
component routerを入れ子にする
app.component('parent', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [{
path: '/...',
component: 'children'}
}]
});
app.component('children', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [{
path: '/child1',
name:'Child1',
component: 'child1'}
},{
path: '/child2/:id',
name:'Child2',
component: 'child2'}
}]
});
親側のcomponentのpathを/...
に設定する。
ページが存在しない場合は、nameは設定しない。
ページを切り替える
view側から切り替える
<a ng-link="['Detail']">詳細ページ</a>
controller側から切り替える
ポイントは、$router
をbindすることです。
bindingsに$router
を設定しないと、$routerがundefinedになってしまいます。
app.component('myComp', {
template: '<div>controllerからページを切り替える</div>',
controller:function(){
var self = this;
self.changePage = function(){
//ページを切り替え
self.$router.navigate(['Hogehoge']);
}
},
bindings: {
$router: '<'
}
});
パラメーターを渡す
パラメータを連携する場合は、$routeConfigで指定するpathをpath/:param/:param2
のようにする必要があります。
app.component('children', {
template: '<ng-outlet></ng-outlet>',
$routeConfig: [{
path: '/child1',
name:'Child1',
component: 'child1'}
},{
path: '/child2/:id',
name:'Child2',
component: 'child2'}
}]
});
ng-linkの設定も下記のように[name,{paramKey:paramValue}]
のようにする必要があります。
<a ng-link="['Detail',{id:100}]">id:100をわたす</a>
パラメーターを受け取る
ページを切り替えた際に連携されたパラメータは$routerOnActivate
で取得することができました。
app.component('child1',{
controller:function(){
this.$routerOnActivate = function(next,prev){
//next ・・・ページ遷移して表示したページ
//prev ・・・ページ遷移元のページ
//child2/:idで、ng-link="['Home',{id:10}]"の場合
console.log(next.params.id);//10
};
}
});
$routerOnActivate
・・・ 遷移で入ってきた場合に発火
$routerOnDeactivate
・・・ 遷移で出いった場合に発火
終わり
ui routerのほうが使い慣れているので、あまりComponent Routerの良さがわかりませんが、
2.0への練習と思いがんばって覚えたいと思います。
でも2.0とも書き方が少し違うみたいです。。。