[AngularJS] ui-router: named views
The ui-router library for AngularJS provides the ability to name views within your application. This is useful for dividing up your application into sections, and changing the content of a section based on the current state.
We use named view to build a simple webpage with 'header','sidebar','content' and 'footer'.
/** * Created by Answer1215 on 12/17/2014. */ angular.module('app', ['ui.router']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('app', { url: '/', views: { 'header': { templateUrl: 'app/common/header.tpl.html' }, 'sidebar': { templateUrl: 'app/common/sidebar.tpl.html' }, 'content': { templateUrl: 'app/common/content.tpl.html' }, 'footer': { templateUrl: 'app/common/footer.tpl.html' } } }); $urlRouterProvider.otherwise('/'); });
<div class="container"> <!-- Header --> <div ui-view="header" class="row"></div> <div class="row"> <!-- Sidebar/Nav --> <div ui-view="sidebar" class="col-xs-3"></div> <!-- Content --> <div ui-view="content" class="col-xs-9"></div> </div> <!-- Footer --> <div ui-view="footer" class="row"></div> </div>
Result:
Now when we click 'One', 'Two' and 'Three', we also want to replace the content accordingly.
alt-one.js:
/** * Created by Answer1215 on 12/17/2014. */ angular.module('app.alt-one', ['ui.router']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('app.alt-one', { url: 'alt-one', views: { // '@': replace the content // if there is just @ without other stuff, it will looking for the parent 'app' root 'content@': { templateUrl: 'app/alt-one/alt-one.content.tpl.html' } } }) })
alt-two.js: we replace the content and header both at the same time.
/** * Created by Answer1215 on 12/17/2014. */ angular.module('app.alt-two', ['ui.router']) .config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('app.alt-two', { url: 'alt-two', views: { 'content@': { templateUrl: 'app/alt-two/alt-two.content.tpl.html' }, 'header@': { templateUrl: 'app/alt-two/alt-two.header.tpl.html' } } }) })
alt-three.js:
/** * Created by Answer1215 on 12/17/2014. */ angular.module('app.alt-three', [ 'ui.router' ]) .config(function($stateProvider) { $stateProvider .state('app.alt-three', { url: 'alt-three', views: { 'content@': { templateUrl: 'app/alt-three/alt-three.content.tpl.html' }, 'header@': { templateUrl: 'app/alt-three/alt-three.header.tpl.html' }, // find the 'alt-three' directory to replace the name view == "one" 'one@app.alt-three': { template: '<div class="alert-info">Sub One</div>' }, // find the 'alt-three' directory to replace the name view == "two" 'two@app.alt-three': { template: '<div class="alert-success">Sub Two</div>' } } } ) }) ;
Read More: https://egghead.io/lessons/angularjs-ui-router-named-views