Search code examples
htmlangularjsuiviewsingle-page-applicationangularjs-ng-template

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:

<head>
   <title> Main page </title>
</head>
<body>
   <div class="row">
    <div class="col-md-10 col-md-offset-1">
       <ui-view></ui-view>
     </div>
   </div>

   <script type = "text/ng-template" id = "/main.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/addStuff.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/searchStuff.html">
   .....
   </script>

   <script type = "text/ng-template" id = "/about.html">
   .....
   </script>
</body>

I have a title for the main page on top of index.ejs. I would also like to have seperate titles for each page so when they are opened in a new tab, I know which one is which. I have tried doing:

<script type = "text/ng-template" id = "/addStuff.html">
    <head>
        <title> Add Stuff </title>
    </head>
    .....

But this doesn't work. Any ideas? Thanks.


Solution

  • 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', function AppCtrl($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:

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