📜 ⬆️ ⬇️

Nested routing in AngularJS

image
In AngularJS , as it is known, there is no possibility of using standard tools to make multi-level routing, in which reloading of lower levels of routes would not lead to the re-creation of top-level elements. The standard $route service initializes the view, controller, and its scope entirely each time the page URL changes.

To solve this problem, several third-party solutions have been written, including the well - known ui-router . For a number of reasons, none of the solutions for some of my projects came up, and I wrote my own library, which I represent here: angular-route-segment .

What does she allow to do?

Demo here: angular-route-segment.com/src/example
Sample code in the example directory on Github.
')
The library serves as a replacement for the standard $route service. Each route is represented as a hierarchical tree of segments , listed through a point, each of which can be configured separately.

 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}); 


It is allowed to use another syntax, without going through the tree:

 $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']}); 


With the help of the app-view-segment directive (replacing the standard ng-view ), the place in the DOM of the page is indicated, where each of the segment levels should be rendered:

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.html (will be loaded into the div#contents element)
 <h4>Section 1</h4> Section 1 contents. <div app-view-segment="1"></div> 


This , .

, , .
, .

, , .

Source: https://habr.com/ru/post/190096/


All Articles