AngularJSのネストされたルーティング

画像

AngularJSでは、ご存じのように、通常の方法でマルチレベルルーティングを行う方法はありません。この方法では、下位レベルのルートをリロードしてもトップレベルの要素が再作成されません。 標準の$route



サービスは、ページURLが変更されるたびに、ビュー、コントローラー、およびそのスコープ全体を初期化します。



この問題を解決するために、よく知られたui-routerなど、いくつかのサードパーティのソリューションが作成されています 。 いくつかの理由で、私のプロジェクトのいくつかで解決策が機能しなかったため、ここで紹介する独自のライブラリ( angular-route-segment)を書きました



彼女は何ができますか?



デモはこちら: angular-route-segment.com/src/example

githubのサンプルディレクトリにあるサンプルのソース。



このライブラリは、標準の$route



サービスの代わりとして機能します。 各ルートは、ポイントを介してリストされたセグメントの階層ツリーのようなチェーンの形式で表され、各セグメントは個別に設定できます。



 angular.module('app').config(function ($routeSegmentProvider) { $routeSegmentProvider. when('/section1', 's1.home'). when('/section1/prefs', 's1.prefs'). when('/section1/:id', 's1.itemInfo.overview'). when('/section1/:id/edit', 's1.itemInfo.edit'). when('/section2', 's2'). segment('s1', { templateUrl: 'templates/section1.html', controller: MainCtrl}). within(). segment('home', { templateUrl: 'templates/section1/home.html'}). segment('itemInfo', { templateUrl: 'templates/section1/item.html', controller: Section1ItemCtrl, dependencies: ['id']}). within(). segment('overview', { templateUrl: 'templates/section1/item/overview.html'}). segment('edit', { templateUrl: 'templates/section1/item/edit.html'}). up(). segment('prefs', { templateUrl: 'templates/section1/prefs.html'}). up(). segment('s2', { templateUrl: 'templates/section2.html', controller: MainCtrl});
      
      







ツリーを経由せずに、別の構文を使用できます。



 $routeSegmentProvider.segment('s1', { templateUrl: 'templates/section1.html', controller: MainCtrl}); $routeSegmentProvider.within('s1').segment('home', { templateUrl: 'templates/section1/home.html'}); $routeSegmentProvider.within('s1').segment('itemInfo', { templateUrl: 'templates/section1/item.html', controller: Section1ItemCtrl, dependencies: ['id']});
      
      







app-view-segment



ディレクティブ(通常のng-view



置き換える)を使用して、ページのDOM内の場所が示され、各セグメントレベルがレンダリングされる必要があります。



index.html

 <ul> <li><a href="/section1">Section 1</a></li> <li><a href="/section2">Section 2</a></li> </ul> <div id="contents" app-view-segment="0"></div>
      
      







section1.htmldiv#contents



要素div#contents



ロードされdiv#contents





 <h4>Section 1</h4> Section 1 contents. <div app-view-segment="1"></div>
      
      







, .



, , .




, .



, , .







All Articles