AngularJS ui-router
Using parent and child named states to prevent all components from refreshing.
by leongaban
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.js"></script>
<div ui-view="tickersPanel" class="tickersPanel"></div>
<div ui-view="tagsPanel" class="tagsPanel"></div>
CSS
.tickersPanel,
.tagsPanel {
position: relative;
width: 400px;
padding: 5px;
}
.tickersPanel {
border: 1px solid black;
}
.tagsPanel {
height: 200px;
border: 1px solid blue;
}
JavaScript
/**
* This setup should only reload the tags state when a ticker is selected from
* the tickers state.
* Check the console to see when controllers are being initialized.
*/
var myApp = angular.module('myApp', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
// Using @ on the view names to refer to the absolute uiViews.
const tickersState = {
name: 'tickers',
url: "",
views: {
'tickersPanel@': {
template: '<h4>Tickers Panel</h4> <ul><li ng-repeat="ticker in $ctrl.tickers"><a href="" ui-sref="tickers.tags({ticker: ticker})">{{ticker}}</a></li></ul>',
bindToController: true,
controllerAs: "$ctrl",
controller: function() {
this.$onInit = function() {
console.info('Tickers Panel $onInit');
this.tickers = ["Ticker1", "Ticker2", "Ticker3"]
}
}
},
'tagsPanel@': {
template: '<p>Select a Ticker to begin<p>'
}
}
};
const tagsState = {
name: 'tickers.tags',
parent: 'tickers',
url: "/:ticker",
views: {
'tagsPanel@': {
template: '<p>Tags for {{$ctrl.ticker}}</p>',
controllerAs: '$ctrl',
bindToController: true,
controller: function($stateParams) {
this.$onInit = function() {
console.info('Tags Panel 2 $onInit');
this.ticker = $stateParams["ticker"];
}
}
}
}
};
$stateProvider
.state(tickersState)
.state(tagsState);
//$stateProvider.state('tickers', {
//});
//$stateProvider.state('tags', {
//});
}
])