node.jsmeanjs

MEAN js dynamic title


how to add dynamic title for each pages of the MEAN js application. in the layout.server.js has defined the title as follows.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>{{title}}</title>

so how can we make dynamic title?


Solution

  • Some people might be mislead thinking that besides it is already dynamic, it can be changed and it is controlled by angular out of the box because of having an expression with {{ }} but that's not quite true.

    In fact {{title}} could mean an expression that should be evaluated against scope.title, however if you take a deeper look at MEAN.js you will see that it is using the swig template engine which also uses {{ }} to define variables. In this case, {{title}} is NOT an angular expression, it is a swig variable which was passed via express/swig and it can be changed in the config/env/default.js (in MEAN.js 0.4.0).

    If you want the title to be changed in the frontend (i.e. possible to change it within angular logic) you have to assign a scope variable to the title element or use a custom directive. Even if, at first, the title value is the one defined using express/swig, angular can take control afterwards and change it accordingly to your needs.

    One solution could be to define the title in your angular states like this:

    .state('some-state', {
        url: '/someurl',
        templateUrl: 'some-path-to-view',
        data: {
            title: 'My new title',
        }
      })
    

    And then listen for the $stateChangeSuccess event to set the title:

    $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        console.log(toState.data.title); // Prints the new title to the console
        // Set the title    
    });
    

    EDIT: First paragraph rewritten for more coherence.