使用UI-Router设置页面标题

时间:2021-10-07 10:55:55

I am migrating my AngularJS based app to use ui-router instead of the built in routing. I have it configured as shown below

我正在迁移基于AngularJS的应用程序来使用ui-router而不是内置的路由。我将它配置为如下所示

.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
    .state('home', {
        url: '/home',
        templateUrl : 'views/home.html',
        data : { pageTitle: 'Home' }

    })
    .state('about', {
        url: '/about',
        templateUrl : 'views/about.html',
        data : { pageTitle: 'About' }
    })
     });

How can I use the pageTitle variable to dynamically set the title of the page? Using the built in routing, I could do

如何使用pageTitle变量来动态设置页面的标题?使用内置的路由,我可以做到

$rootScope.$on("$routeChangeSuccess", function(currentRoute, previousRoute){
    $rootScope.pageTitle = $route.current.data.pageTitle;
  });

and then bind the variable in HTML as shown below

然后在HTML中绑定变量,如下所示。

<title ng-bind="$root.pageTitle"></title>

Is there a similar event that I can hook into using ui-router? I noticed that there are 'onEnter' and 'onExit' functions but they seem to be tied to each state and will require me to repeat code to set the $rootScope variable for each state.

是否有类似的事件我可以用ui-路由器连接?我注意到有“onEnter”和“onExit”函数,但它们似乎与每个状态绑定在一起,需要我重复代码来为每个状态设置$rootScope变量。

14 个解决方案

#1


103  

Use $stateChangeSuccess.

使用stateChangeSuccess美元。

You can put it in a directive:

你可以把它写在指令里:

app.directive('updateTitle', ['$rootScope', '$timeout',
  function($rootScope, $timeout) {
    return {
      link: function(scope, element) {

        var listener = function(event, toState) {

          var title = 'Default Title';
          if (toState.data && toState.data.pageTitle) title = toState.data.pageTitle;

          $timeout(function() {
            element.text(title);
          }, 0, false);
        };

        $rootScope.$on('$stateChangeSuccess', listener);
      }
    };
  }
]);

And:

和:

<title update-title></title>

Demo: http://run.plnkr.co/8tqvzlCw62Tl7t4j/#/home

演示:http://run.plnkr.co/8tqvzlCw62Tl7t4j/ /回家

Code: http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview

代码:http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview

Even with $stateChangeSuccess the $timeout has been needed for the history to be correct, at least when I've tested myself.

即使有了$stateChangeSuccess,历史记录也需要$timeout,至少在我测试自己的时候是这样的。


Edit: Nov 24, 2014 - Declarative approach:

编辑:2014年11月24日-声明式方法:

app.directive('title', ['$rootScope', '$timeout',
  function($rootScope, $timeout) {
    return {
      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);
      }
    };
  }
]);

And:

和:

<title>{{title}}</title>

Demo: http://run.plnkr.co/d4s3qBikieq8egX7/#/credits

演示:http://run.plnkr.co/d4s3qBikieq8egX7/ /学分

Code: http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview

代码:http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview

#2


86  

There is a another way of doing this by combining most of the answers here already. I know this is already answered but I wanted to show the way I dynamically change page titles with ui-router.

还有另一种方法,把大部分的答案组合在一起。我知道这已经得到了回答,但我想展示如何使用ui-router动态更改页面标题。

If you take a look at ui-router sample app, they use the angular .run block to add the $state variable to $rootScope.

如果你看一下ui-router样本应用程序,他们使用具有棱角的.run块将$state变量添加到$rootScope。

// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.
// For example, <li ng-class="{ active: $state.includes('contacts.list') }"> 
// will set the <li> to active whenever 'contacts.list' or one of its 
// decendents is active.

.run([ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
  $rootScope.$state = $state;
  $rootScope.$stateParams = $stateParams;
}])

With this defined you can then easily dynamically update your page title with what you have posted but modified to use the defined state:

有了这个定义,您就可以轻松地动态地更新您的页面标题,并将您发布的内容修改为使用已定义的状态:

Setup the state the same way:

以相同的方式设置状态:

.state('home', {
    url: '/home',
    templateUrl : 'views/home.html',
    data : { pageTitle: 'Home' }
})

But edit the html a bit...

但是编辑一下html…

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

I can't say this is any better than the answers before... but was easier for me to understand and implement. Hope this helps someone!

我不能说这比之前的答案好。但是对我来说更容易理解和实施。希望这可以帮助别人!

#3


17  

The angular-ui-router-title plugin makes it easy to update the page title to a static or dynamic value based on the current state. It correctly works with browser history, too.

angular-ui-router-title插件可以根据当前状态将页面标题更新为静态或动态值。它也正确地处理了浏览器历史。

#4


11  

$stateChangeSuccess is now deprecated in UI-Router 1.x and disabled by default. You'll now need to use the new $transition service.

$stateChangeSuccess在UI-Router 1中被弃用。在默认情况下被禁用。现在需要使用新的$transition服务。

A solution isn't too difficult once you understand how $transition works. I got some help from @troig in understanding it all. Here's what I came up with for updating the title.

一旦理解了$transition是如何工作的,解决方案就不是很难了。我从@troig那里得到了一些帮助。以下是我更新标题时想到的。

Put this in your Angular 1.6 application. Note that I'm using ECMAScript 6 syntax; if you are not, you'll need e.g. to change let to var.

把这个放到角1。6的应用中。注意,我使用的是ECMAScript 6语法;如果不是,就需要将let改为var。

.run(function($transitions, $window) {
    $transitions.onSuccess({}, (transition) => {
        let title = transition.to().title;
        if (title) {
            if (title instanceof Function) {
                title = title.call(transition.to(), transition.params());
            }
            $window.document.title = title;
        }
    });

Then just add a title string to your state:

然后添加一个标题字符串到你的状态:

$stateProvider.state({
    name: "foo",
    url: "/foo",
    template: "<foo-widget layout='row'/>",
    title: "Foo Page""
});

That will make the words "Foo Page" show up in the title. (If a state has no title, the page title will not be updated. It would be a simple thing to update the code above to provide a default title if a state does not indicate one.)

这将使单词“Foo Page”出现在标题中。(如果一个州没有标题,页面标题将不会被更新。更新上面的代码以提供默认标题是一件简单的事情,如果一个状态不指示一个标题)。

The code also allows you to use a function for title. The this used to call the function will be the state itself, and the one argument will be the state parameters, like this example:

代码还允许您使用一个函数作为标题。用来调用函数的参数将是状态本身,一个参数将是状态参数,就像这个例子:

$stateProvider.state({
    name: "bar",
    url: "/bar/{code}",
    template: "<bar-widget code='{{code}}' layout='row'/>",
    title: function(params) {
        return `Bar Code ${params.code}`;
    }
});

For the URL path /bar/code/123 that would show "Bar Code 123" as the page title. Note that I'm using ECMAScript 6 syntax to format the string and extract params.code.

对于URL路径/bar/code/123,将显示“bar code 123”作为页面标题。注意,我正在使用ECMAScript 6语法来格式化字符串并提取params.code。

It would be nice if someone who had the time would put something like this into a directive and publish it for everyone to use.

如果有时间的人能把这样的东西放到一个指令里,并把它发布给所有人使用,那就太好了。

#5


5  

Attaching $state to $rootscope to use anywhere in the app.

将$state附加到$rootscope以在应用程序的任何地方使用。

app.run(['$rootScope', '$state', '$stateParams',
    function ($rootScope,   $state,   $stateParams) {

        // It's very handy to add references to $state and $stateParams to the $rootScope
        // so that you can access them from any scope within your applications.For example,
        // <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
        // to active whenever 'contacts.list' or one of its decendents is active.
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    }
  ]
)
<title ng-bind="$state.current.name + ' - ui-router'">about - ui-router</title>

#6


5  

I found this way really easy:

我发现这个方法很简单:

  .state('app.staff.client', {
    url: '/client/mine',
    title: 'My Clients'})

and then in my HTML like this:

然后在我的HTML中

<h3>{{ $state.current.title }}</h3>

#7


3  

Just update window.document.title:

只是更新window.document.title:

.state('login', {
   url: '/login',
   templateUrl: "/Login",
   controller: "loginCtrl",
   onEnter: function($window){$window.document.title = "App Login"; }
})

That way 'ng-app' does not need to move up to the HTML tag and can stay on the body or lower.

这样,“ng-app”就不需要移动到HTML标签上,可以停留在正文或下面。

#8


3  

I'm using ngMeta, which works well for not only setting page title but descriptions as well. It lets you set a specific title/description for each state, defaults for when a title/description is not specified, as well as default title suffixes (i.e., ' | MySiteName') and author value.

我正在使用ngMeta,它不仅可以很好地设置页面标题,还可以很好地设置描述。它允许您为每个状态设置一个特定的标题/描述,默认为没有指定标题/描述,以及默认的标题/描述后缀。、“| MySiteName”和作者的价值。

$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'views/home.html',
    controller: 'HomeController',
    meta: {
      'title': 'Home',
      'titleSuffix': ' | MySiteName',
      'description': 'This is my home page description lorem ipsum.'
    },
  })

#9


2  

You are actually really close with your first answer/question. Add your title as a data object:

你真的很接近你的第一个答案/问题。添加您的标题作为数据对象:

.state('home', {
    url: '/home',
    templateUrl : 'views/home.html',
    data : { pageTitle: 'Home' }
})

In your index.html bind the data directly to the page title:

在您的索引。html将数据直接绑定到页面标题:

<title data-ng-bind="$state.current.data.pageTitle + ' - Optional text'">Failsafe text</title>

#10


1  

I ended up with this combination of Martin's and tasseKATT's answers - simple and without any template related stuff:

我把Martin和tasseKATT的答案结合在一起——简单,没有任何模板相关的东西:

$rootScope.$on("$stateChangeSuccess", function (event, toState) {
   $timeout(function () { // Needed to ensure the title is changed *after* the url so that history entries are correct.
     $window.document.title = toState.name; 
   });
});

#11


1  

Why not just:

为什么不直接:

$window.document.title = 'Title';

UPDATE: Full Directive Code

更新:完整的指令代码

var DIRECTIVE = 'yourPageTitle';

yourPageTitle.$inject = ['$window'];
function yourPageTitle($window: ng.IWindowService): ng.IDirective {

    return {
        link: (scope, element, attrs) => {

            attrs.$observe(DIRECTIVE, (value: string) => {

                $window.document.title = value;
            });
        }
    }
}

directive(DIRECTIVE, yourPageTitle);

Then in every page you would just include this directive:

那么,在每一页中,你只会包括这个指示:

<section
    your-page-title="{{'somePage' | translate}}">

#12


0  

If you are using ES6, this works just fine :).

如果您正在使用ES6,那么这个功能就很好:)。

class PageTitle {
    constructor($compile, $timeout) {
        this.restrict = 'A';
        this._$compile = $compile;
        this.$timeout = $timeout;
    }

    compile(element) {
        return this.link.bind(this);
    }

    link(scope, element, attrs, controller) {
        let defaultTitle = attrs.pageTitle ? attrs.pageTitle : "My Awesome Sauce Site";
        let listener = function(event, toState) {
            let title = defaultTitle;
            if (toState.data && toState.data.title) title = toState.data.title + ' | ' + title;
            $('html head title').text(title);
        };
        scope.$on('$stateChangeStart', listener);
    }
}

export function directiveFactory($compile) {
    return new PageTitle($compile);
}

directiveFactory.injections = ['$compile', '$timeout'];

export default PageTitle;

#13


0  

Maybe you can try this directive.

也许你可以试试这个指令。

https://github.com/afeiship/angular-dynamic-title

https://github.com/afeiship/angular-dynamic-title

Here is the example:

html:

<title dynamic-title>Title</title>

<a href="javascript:;" ui-sref="state1">State1 page</a>
<a href="javascript:;" ui-sref="state2">State2 page</a>

javascript:

var TestModule = angular.module('TestApp', ['ui.router','nx.widget'])
    .config(function ($stateProvider, $urlRouterProvider) {
      //
      // For any unmatched url, redirect to /state1
      $urlRouterProvider.otherwise("/state1");
      //
      // Now set up the states
      $stateProvider
        .state('state1', {
          url: "/state1",
          templateUrl: "partials/state1.html",
          data:{
            pageTitle:'State1 page title11111'
          }
        })
        .state('state2', {
          url: "/state2",
          templateUrl: "partials/state2.html",data:{
            pageTitle:'State2 page title222222'
          }
        });
    })
    .controller('MainCtrl', function ($scope) {
      console.log('initial ctrl!');
    });

#14


0  

For Updated UI-Router 1.0.0+ versions, (https://ui-router.github.io/guide/ng1/migrate-to-1_0)

对于更新的UI-Router 1.0.0+版本,(https://ui-router.github.io/guide/ng1/migrate-to-1_0)

Refer to following code

参考代码

app.directive('pageTitle', [
    '$rootScope',
    '$timeout',
    '$transitions',
    function($rootScope, $timeout,$transitions) {
        return {
            restrict: 'A',
            link: function() {
                var listener = function($transitions) {
                    var default_title = "DEFAULT_TITLE";
                    $timeout(function() {
                        	$rootScope.page_title = ($transitions.$to().data && $transitions.$to().data.pageTitle)
                            ? default_title + ' - ' + $transitions.$to().data.pageTitle : default_title;
                    	
                        
                    });
                };
                $transitions.onSuccess({ }, listener);
            }
        }
    }
])

Add following to your index.html:

在你的index.html中添加以下内容:

<title page-title ng-bind="page_title"></title>

#1


103  

Use $stateChangeSuccess.

使用stateChangeSuccess美元。

You can put it in a directive:

你可以把它写在指令里:

app.directive('updateTitle', ['$rootScope', '$timeout',
  function($rootScope, $timeout) {
    return {
      link: function(scope, element) {

        var listener = function(event, toState) {

          var title = 'Default Title';
          if (toState.data && toState.data.pageTitle) title = toState.data.pageTitle;

          $timeout(function() {
            element.text(title);
          }, 0, false);
        };

        $rootScope.$on('$stateChangeSuccess', listener);
      }
    };
  }
]);

And:

和:

<title update-title></title>

Demo: http://run.plnkr.co/8tqvzlCw62Tl7t4j/#/home

演示:http://run.plnkr.co/8tqvzlCw62Tl7t4j/ /回家

Code: http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview

代码:http://plnkr.co/edit/XO6RyBPURQFPodoFdYgX?p=preview

Even with $stateChangeSuccess the $timeout has been needed for the history to be correct, at least when I've tested myself.

即使有了$stateChangeSuccess,历史记录也需要$timeout,至少在我测试自己的时候是这样的。


Edit: Nov 24, 2014 - Declarative approach:

编辑:2014年11月24日-声明式方法:

app.directive('title', ['$rootScope', '$timeout',
  function($rootScope, $timeout) {
    return {
      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);
      }
    };
  }
]);

And:

和:

<title>{{title}}</title>

Demo: http://run.plnkr.co/d4s3qBikieq8egX7/#/credits

演示:http://run.plnkr.co/d4s3qBikieq8egX7/ /学分

Code: http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview

代码:http://plnkr.co/edit/NpzQsxYGofswWQUBGthR?p=preview

#2


86  

There is a another way of doing this by combining most of the answers here already. I know this is already answered but I wanted to show the way I dynamically change page titles with ui-router.

还有另一种方法,把大部分的答案组合在一起。我知道这已经得到了回答,但我想展示如何使用ui-router动态更改页面标题。

If you take a look at ui-router sample app, they use the angular .run block to add the $state variable to $rootScope.

如果你看一下ui-router样本应用程序,他们使用具有棱角的.run块将$state变量添加到$rootScope。

// It's very handy to add references to $state and $stateParams to the $rootScope
// so that you can access them from any scope within your applications.
// For example, <li ng-class="{ active: $state.includes('contacts.list') }"> 
// will set the <li> to active whenever 'contacts.list' or one of its 
// decendents is active.

.run([ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
  $rootScope.$state = $state;
  $rootScope.$stateParams = $stateParams;
}])

With this defined you can then easily dynamically update your page title with what you have posted but modified to use the defined state:

有了这个定义,您就可以轻松地动态地更新您的页面标题,并将您发布的内容修改为使用已定义的状态:

Setup the state the same way:

以相同的方式设置状态:

.state('home', {
    url: '/home',
    templateUrl : 'views/home.html',
    data : { pageTitle: 'Home' }
})

But edit the html a bit...

但是编辑一下html…

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

I can't say this is any better than the answers before... but was easier for me to understand and implement. Hope this helps someone!

我不能说这比之前的答案好。但是对我来说更容易理解和实施。希望这可以帮助别人!

#3


17  

The angular-ui-router-title plugin makes it easy to update the page title to a static or dynamic value based on the current state. It correctly works with browser history, too.

angular-ui-router-title插件可以根据当前状态将页面标题更新为静态或动态值。它也正确地处理了浏览器历史。

#4


11  

$stateChangeSuccess is now deprecated in UI-Router 1.x and disabled by default. You'll now need to use the new $transition service.

$stateChangeSuccess在UI-Router 1中被弃用。在默认情况下被禁用。现在需要使用新的$transition服务。

A solution isn't too difficult once you understand how $transition works. I got some help from @troig in understanding it all. Here's what I came up with for updating the title.

一旦理解了$transition是如何工作的,解决方案就不是很难了。我从@troig那里得到了一些帮助。以下是我更新标题时想到的。

Put this in your Angular 1.6 application. Note that I'm using ECMAScript 6 syntax; if you are not, you'll need e.g. to change let to var.

把这个放到角1。6的应用中。注意,我使用的是ECMAScript 6语法;如果不是,就需要将let改为var。

.run(function($transitions, $window) {
    $transitions.onSuccess({}, (transition) => {
        let title = transition.to().title;
        if (title) {
            if (title instanceof Function) {
                title = title.call(transition.to(), transition.params());
            }
            $window.document.title = title;
        }
    });

Then just add a title string to your state:

然后添加一个标题字符串到你的状态:

$stateProvider.state({
    name: "foo",
    url: "/foo",
    template: "<foo-widget layout='row'/>",
    title: "Foo Page""
});

That will make the words "Foo Page" show up in the title. (If a state has no title, the page title will not be updated. It would be a simple thing to update the code above to provide a default title if a state does not indicate one.)

这将使单词“Foo Page”出现在标题中。(如果一个州没有标题,页面标题将不会被更新。更新上面的代码以提供默认标题是一件简单的事情,如果一个状态不指示一个标题)。

The code also allows you to use a function for title. The this used to call the function will be the state itself, and the one argument will be the state parameters, like this example:

代码还允许您使用一个函数作为标题。用来调用函数的参数将是状态本身,一个参数将是状态参数,就像这个例子:

$stateProvider.state({
    name: "bar",
    url: "/bar/{code}",
    template: "<bar-widget code='{{code}}' layout='row'/>",
    title: function(params) {
        return `Bar Code ${params.code}`;
    }
});

For the URL path /bar/code/123 that would show "Bar Code 123" as the page title. Note that I'm using ECMAScript 6 syntax to format the string and extract params.code.

对于URL路径/bar/code/123,将显示“bar code 123”作为页面标题。注意,我正在使用ECMAScript 6语法来格式化字符串并提取params.code。

It would be nice if someone who had the time would put something like this into a directive and publish it for everyone to use.

如果有时间的人能把这样的东西放到一个指令里,并把它发布给所有人使用,那就太好了。

#5


5  

Attaching $state to $rootscope to use anywhere in the app.

将$state附加到$rootscope以在应用程序的任何地方使用。

app.run(['$rootScope', '$state', '$stateParams',
    function ($rootScope,   $state,   $stateParams) {

        // It's very handy to add references to $state and $stateParams to the $rootScope
        // so that you can access them from any scope within your applications.For example,
        // <li ng-class="{ active: $state.includes('contacts.list') }"> will set the <li>
        // to active whenever 'contacts.list' or one of its decendents is active.
        $rootScope.$state = $state;
        $rootScope.$stateParams = $stateParams;
    }
  ]
)
<title ng-bind="$state.current.name + ' - ui-router'">about - ui-router</title>

#6


5  

I found this way really easy:

我发现这个方法很简单:

  .state('app.staff.client', {
    url: '/client/mine',
    title: 'My Clients'})

and then in my HTML like this:

然后在我的HTML中

<h3>{{ $state.current.title }}</h3>

#7


3  

Just update window.document.title:

只是更新window.document.title:

.state('login', {
   url: '/login',
   templateUrl: "/Login",
   controller: "loginCtrl",
   onEnter: function($window){$window.document.title = "App Login"; }
})

That way 'ng-app' does not need to move up to the HTML tag and can stay on the body or lower.

这样,“ng-app”就不需要移动到HTML标签上,可以停留在正文或下面。

#8


3  

I'm using ngMeta, which works well for not only setting page title but descriptions as well. It lets you set a specific title/description for each state, defaults for when a title/description is not specified, as well as default title suffixes (i.e., ' | MySiteName') and author value.

我正在使用ngMeta,它不仅可以很好地设置页面标题,还可以很好地设置描述。它允许您为每个状态设置一个特定的标题/描述,默认为没有指定标题/描述,以及默认的标题/描述后缀。、“| MySiteName”和作者的价值。

$stateProvider
  .state('home', {
    url: '/',
    templateUrl: 'views/home.html',
    controller: 'HomeController',
    meta: {
      'title': 'Home',
      'titleSuffix': ' | MySiteName',
      'description': 'This is my home page description lorem ipsum.'
    },
  })

#9


2  

You are actually really close with your first answer/question. Add your title as a data object:

你真的很接近你的第一个答案/问题。添加您的标题作为数据对象:

.state('home', {
    url: '/home',
    templateUrl : 'views/home.html',
    data : { pageTitle: 'Home' }
})

In your index.html bind the data directly to the page title:

在您的索引。html将数据直接绑定到页面标题:

<title data-ng-bind="$state.current.data.pageTitle + ' - Optional text'">Failsafe text</title>

#10


1  

I ended up with this combination of Martin's and tasseKATT's answers - simple and without any template related stuff:

我把Martin和tasseKATT的答案结合在一起——简单,没有任何模板相关的东西:

$rootScope.$on("$stateChangeSuccess", function (event, toState) {
   $timeout(function () { // Needed to ensure the title is changed *after* the url so that history entries are correct.
     $window.document.title = toState.name; 
   });
});

#11


1  

Why not just:

为什么不直接:

$window.document.title = 'Title';

UPDATE: Full Directive Code

更新:完整的指令代码

var DIRECTIVE = 'yourPageTitle';

yourPageTitle.$inject = ['$window'];
function yourPageTitle($window: ng.IWindowService): ng.IDirective {

    return {
        link: (scope, element, attrs) => {

            attrs.$observe(DIRECTIVE, (value: string) => {

                $window.document.title = value;
            });
        }
    }
}

directive(DIRECTIVE, yourPageTitle);

Then in every page you would just include this directive:

那么,在每一页中,你只会包括这个指示:

<section
    your-page-title="{{'somePage' | translate}}">

#12


0  

If you are using ES6, this works just fine :).

如果您正在使用ES6,那么这个功能就很好:)。

class PageTitle {
    constructor($compile, $timeout) {
        this.restrict = 'A';
        this._$compile = $compile;
        this.$timeout = $timeout;
    }

    compile(element) {
        return this.link.bind(this);
    }

    link(scope, element, attrs, controller) {
        let defaultTitle = attrs.pageTitle ? attrs.pageTitle : "My Awesome Sauce Site";
        let listener = function(event, toState) {
            let title = defaultTitle;
            if (toState.data && toState.data.title) title = toState.data.title + ' | ' + title;
            $('html head title').text(title);
        };
        scope.$on('$stateChangeStart', listener);
    }
}

export function directiveFactory($compile) {
    return new PageTitle($compile);
}

directiveFactory.injections = ['$compile', '$timeout'];

export default PageTitle;

#13


0  

Maybe you can try this directive.

也许你可以试试这个指令。

https://github.com/afeiship/angular-dynamic-title

https://github.com/afeiship/angular-dynamic-title

Here is the example:

html:

<title dynamic-title>Title</title>

<a href="javascript:;" ui-sref="state1">State1 page</a>
<a href="javascript:;" ui-sref="state2">State2 page</a>

javascript:

var TestModule = angular.module('TestApp', ['ui.router','nx.widget'])
    .config(function ($stateProvider, $urlRouterProvider) {
      //
      // For any unmatched url, redirect to /state1
      $urlRouterProvider.otherwise("/state1");
      //
      // Now set up the states
      $stateProvider
        .state('state1', {
          url: "/state1",
          templateUrl: "partials/state1.html",
          data:{
            pageTitle:'State1 page title11111'
          }
        })
        .state('state2', {
          url: "/state2",
          templateUrl: "partials/state2.html",data:{
            pageTitle:'State2 page title222222'
          }
        });
    })
    .controller('MainCtrl', function ($scope) {
      console.log('initial ctrl!');
    });

#14


0  

For Updated UI-Router 1.0.0+ versions, (https://ui-router.github.io/guide/ng1/migrate-to-1_0)

对于更新的UI-Router 1.0.0+版本,(https://ui-router.github.io/guide/ng1/migrate-to-1_0)

Refer to following code

参考代码

app.directive('pageTitle', [
    '$rootScope',
    '$timeout',
    '$transitions',
    function($rootScope, $timeout,$transitions) {
        return {
            restrict: 'A',
            link: function() {
                var listener = function($transitions) {
                    var default_title = "DEFAULT_TITLE";
                    $timeout(function() {
                        	$rootScope.page_title = ($transitions.$to().data && $transitions.$to().data.pageTitle)
                            ? default_title + ' - ' + $transitions.$to().data.pageTitle : default_title;
                    	
                        
                    });
                };
                $transitions.onSuccess({ }, listener);
            }
        }
    }
])

Add following to your index.html:

在你的index.html中添加以下内容:

<title page-title ng-bind="page_title"></title>