Skip to content Skip to sidebar Skip to footer

Angularjs Trouble Adding Page Titles

I am writing a web app using AngularJS. It is not a single page application but all my codes are in one file- index.ejs. So my set up for index.ejs roughly looks like this:

Solution 1:

You should use ui-router. In which case you can add a top level controller on the body or html element, for example <html ng-app="my-app" ng-controller="AppCtrl">

And add a '$stateChangeSuccess' listener whenever a new route is loaded...

.controller('AppCtrl', functionAppCtrl($scope) {

    $scope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
        if (angular.isDefined(toState.data.pageTitle)) {
            $scope.pageTitle = toState.data.pageTitle;
        }
    });
})

Then in the route definition you can add a property called data.pageTitle

$stateProvider.state( 'profile', {
        url: '/profile',
        views: {
            "main": {
                controller: 'ProfileCtrl',
                templateUrl: 'profile/profile.tpl.html'
            }
        },
        data:{ 
           pageTitle: 'Profile' 
        }
    })

Then in your main index.html file, you can bind the pageTitle attribute:

<titleng-bind="pageTitle"></title>

Solution 2:

The most important part is the you move the directive ng-app on the <html> tag if it's not already in there.

Thus all the html page is covered by angular.

Eg:

<htmlng-app="app">

  ...

</html>

Then it's really your choice. You can use a custom directive to wrap the title, generate a service or just use the {{ }} syntax.

Post a Comment for "Angularjs Trouble Adding Page Titles"