Updating title tag using AngularJS and UI-Router

后端 未结 3 756
星月不相逢
星月不相逢 2020-12-14 10:52

I am running into a weird issue while trying to set the title of the page using the name of the current state (via ui-router).

Actually, the issue is not with settin

相关标签:
3条回答
  • 2020-12-14 11:09

    I have a similar situation like yours and I do it like the following. You can put that in your main app run block like following. I had

     angular.module('myApp').run([
        '$log', '$rootScope', '$window', '$state', '$location',
        function($log, $rootScope, $window, $state, $location) {
    
            $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
                if (toState.title) {
                    $rootScope.pageTitle = toState.title;
                }
            });
    
            $rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
                // something else 
            });
    
            $state.go('home');
        }
     ]);
    

    and in the html head i have

    <html class="no-js" class="ng-app" ng-app="..." id="ng-app">
        <head>
         ....
           <title ng-bind="pageTitle"></title>
    

    hope this works for you.

    PS: Please consult https://docs.angularjs.org/guide/module for details.

    0 讨论(0)
  • 2020-12-14 11:28

    I had a 'similar' situation... and answered it here.

    It basically defines $rootScope.$state = $state inside of the run method of angular. That allows us to access current states info in templates.

    <title ng-bind="$state.current.data.pageTitle"></title>
    

    The key is defining it on the $rootScope in the run method.

    0 讨论(0)
  • 2020-12-14 11:28

    I wrote the angular-ui-router-title plugin for this. You can use it to update the page title to a static or dynamic value based on the current state. It correctly works with browser history, too.

    0 讨论(0)
提交回复
热议问题