How do I change title that is displayed outside of a controller scope depending on current controller provided by router? Basically, I have mainMenu controller that is loaded when specific route is called. However, outside of the view, there is partial included which is a header. I want to change output inside of a header depending on the current route. I added code structure below:
index.html
<div ng-include="'partials/header.html'"></div>
<div ng-view></div>
/partials/header.html
<header ng-controller="HeaderCtrl">
<h1>{{ currentTitle }}</h1>
</header>
/partials/main-menu.html
<div ng-controller="MainMenuCtrl">
</div>
Router
var TaskApp = angular.module('TaskApp', [
'ngRoute',
'taskAppControllers'
]);
TaskApp.config(['$routeProvider',
function($routeProvider){
$routeProvider.
when('/main-menu', {
templateUrl: "partials/main-menu.html",
controller: "MainMenuCtrl"
}).
otherwise({
redirectTo: "/"
});
}]);
Controllers:
var taskAppControllers = angular.module('taskAppControllers',[]);
taskAppControllers.controller('TaskAppCtrl',[function(){}]);
taskAppControllers.controller('DesktopCtrl',[function(){}]);
taskAppControllers.controller('MainMenuCtrl', ['$scope','$http',
function($scope, $http){
$http.get('data/main-menu.json?' + Math.random()).success(function(data){
$scope.mainMenuOptions = data;
});
$scope.currentTitle = "Main menu"
}]);
taskAppControllers.controller('HeaderCtrl', ['$scope',
function($scope){
//
}]);
You could add one more property with each route options, which will something like title
when('/main-menu', {
templateUrl: "partials/main-menu.html",
controller: "MainMenuCtrl",
title: 'Main Page'
}).
Then place $routeChangeSuccess(it gets fired when route changes are succeeded) event inside HeaderCtrl
, and then do grab current route object and get title from it and set it to currentTitle
scope variable
$scope.$on('$routeChangeSuccess', function(event, current) {
$scope.currentTitle = current.title;
});