AngularJS trouble adding page titles

2019-09-10 02:50发布

问题:

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.

回答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', 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>


回答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:

<html ng-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.