无法更新 angular 1 个关于路线更改的应用程序的标题

unable to update the title of angular 1 application on route change

以下指令提供当前路由值

(function () {
    var titleDirective=angular.module('titleDirective',[]);
    titleDirective.directive('testTitle',function ($rootScope, $timeout) {
        return {
            restrict: 'E',
            link: function() {
                var listener = function(event, toState) {
                    $timeout(function() {
                        $rootScope.title = (toState.data && toState.data.pageTitle)
                            ? toState.data.pageTitle
                            : 'Default title';
                    });
                };
                $rootScope.$on('$stateChangeSuccess', listener);
            }
        };
    })
})();

我已经定义了如下所示的路线

 .state('admin.signIn', {
            url: '/signIn',
            templateUrl: 'credentials/signIn.html',
            controller: 'loginCtrl',
            data : { pageTitle: 'Home' }
        })

当我尝试使用如下所示的指令时 index.html

<test-title>{{title}}</test-title>

但不确定如何在更改路线时更新 html 的标题标签中的值

<title>Retailer Application</title>

不确定如何使用 {{title}} 来表现得像标题

请建议一种方法

将您的指令更新为:

myApp.directive('testTitle', function($rootScope, $timeout) {
  return {
    restrict: 'E',
    template: `<title>{{$root.title}}</title>`,
    link: function() {
      var listener = function(event, toState) {
        $timeout(function() {
          $rootScope.title = (toState.data && toState.data.pageTitle) ? toState.data.pageTitle : 'Default title';
        });
      };
      $rootScope.$on('$stateChangeSuccess', listener);
    }
  };
});

在这里,当您在模板中使用 $rootScope 作为标题变量时,您必须使用 {{$root.title}}。之后只需在 index.html

的 head 部分添加 test-title 指令

Working Plunker

还要确保您使用的是 ui-router 的 0.4.2 版本。 ui-router $stateChangeSuccess 事件的最新版本 (1.x) 已弃用。请改用 $transitions.onSuccess

Official Documentation & issue