Reputation: 5298
I have an Angular app using the Ui Router for routing purposes. Each time I change the router, I would like to change the header of the page, and it seems like the $stateProvider would be the easiest way to do that. I have something like this for the $stateProvider:
$stateProvider
.state('index', {
url: "/",
views: {
"rightContainer": { templateUrl: "viewA.html" },
},
controller: function ($scope) {
$scope.data.header = "Header 1"
}
})
.state('details', {
url: "/details",
views: {
"rightContainer": { templateUrl: "ViewB.html" },
},
controller: function ($scope) {
$scope.data.header = "Header 2"
}
});
I then want to have the header:
<div data-ng-controller="mainCtrl">
<div class='bg'>{{data.header}}</div>
</div>
Upvotes: 0
Views: 5819
Reputation: 5735
The .state
object has a data
property for exactly what your trying to achieve. Just add data: {header: "Header 1"}
to .state
like so:
$stateProvider
.state('index', {
url: "/",
views: {
"rightContainer": { templateUrl: "viewA.html" },
},
data: {header: "Header 1"}
})
Edit/Update
To access that data
for page titles etc, its best if you use one controller
for the index.html <head>
, and use $scope.$on
to push changes to a $scope.header
on route change events. I would recommend having a look at the https://github.com/ngbp/ngbp project boilerplate for a working example.
HTML
https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/index.html
<html ng-app="myApp" ng-controller="AppCtrl">
<head>
<title ng-bind="header"></title>
...
</head>
app.js
https://github.com/ngbp/ngbp/blob/v0.3.2-release/src/app/app.js
.controller( 'AppCtrl', function AppCtrl ( $scope, $location ) {
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
if ( angular.isDefined( toState.data.header ) ) {
$scope.header = toState.data.header;
}
});
Upvotes: 1
Reputation: 32716
You can use data https://github.com/angular-ui/ui-router/wiki#attach-custom-data-to-state-objects or just an other approach
.run(function ($state,$rootScope$filter,WindowUtils) {
$rootScope.$state = $state;
$rootScope.$on('$stateChangeSuccess', function(event, toState) {
var stateName = toState.name;
//switch
WindowUtils.setTitle(stateName);
});
})
.factory('WindowUtils', function($window) {
return {
setTitle:function(title){
var sep = ' - ';
var current = $window.document.title.split(sep)[0];
$window.document.title = current + sep + title;
}
};
})
Upvotes: 1