mshwf
mshwf

Reputation: 7449

How to change URL of the page in AngularJS routing in one controller?

this is the routing configuration:

tapp.config(function ($routeProvider) {
    $routeProvider.when('/', {
        title: 'Home',
        controller: 'tCtrlr',
        templateUrl: '../HTML/Index.html',
    }),
    $routeProvider.when('/Tasks', {
        title: 'Tasks',
        controller: 'tCtrlr',
        templateUrl: '../HTML/Tasks.html',
    }),
    $routeProvider.when('/MyTasks', {
        title: 'My Tasks',
        controller: 'tCtrlr',
        templateUrl: '../HTML/MyTasks.html',
    })

When navigating between the pages the title is not set, I've read some SO threads regarding to this issue, but most assume I have a controller for every page. So how could I get the title property in the when function?

Upvotes: 0

Views: 450

Answers (1)

Muhammed Neswine
Muhammed Neswine

Reputation: 2047

The way I do it is quite simple. In route configuration you define title:

.when('/dashboard', {
  title : 'My Dashboard',
  templateUrl : 'templates/sections/app-dashboard.html',
  controller  : 'DashboardController'
})

then you listen $routeChangeSuccess event and just set document.title. In application run block (the best place for this).

app.run(['$rootScope', '$route', function($rootScope, $route) {
  $rootScope.$on('$routeChangeSuccess', function() {
    document.title = $route.current.title;
  });
}]);

The benefit of this approach is that it allows you to avoid one more binding ng-bind="title".

Upvotes: 1

Related Questions