Angular ui router, title dynamic

為{幸葍}努か 提交于 2020-01-15 20:56:09

问题


How I spend a parameter title of the post, to display the browser's title?

I use pageTitle parameter on my route, but if put directly: slug as a value, not works.

.state('posts',{
    url         : '/blog/:slug',
    templateUrl : 'content/templates/single.html',
    controller  : 'SinglePostController',
    data: {
        pageTitle: 'title'
    },
    access: {
        requiredLogin: false
    }
})

回答1:


The data : {} setting is static.

see similar:

  • Accessing parameters in custom data

If you want some dynamic feature use resolve : {}

Some links to examples and Q & A about resolve

  • Angularjs ui-router abstract state with resolve

EXTEND: A simple (really naive but working) example how to use resolve and $rootScope to manage browser title (check it here):

$stateProvider
  .state('home', {
      url: "/home",
      templateUrl: 'tpl.html',
      resolve: {
        'title': ['$rootScope', function($rootScope){
          $rootScope.title = "Other title";
        }],
      }
  })
  .state('parent', {
      url: "/parent",
      templateUrl: 'tpl.html',
      resolve: {
        'title': ['$rootScope', function($rootScope){
          $rootScope.title = "Title from Parent";
        }],
      }
  })
  .state('parent.child', { 
      url: "/child",
      templateUrl: 'tpl.html',
      controller: 'ChildCtrl',
      resolve: {
        'titleFromChild': ['$rootScope', function($rootScope){
          $rootScope.title = "Title from Child";
        }],
      }
  })

And this could be the html

<!DOCTYPE html>
<html ng-app="MyApp" ng-strict-di>

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

Try it here

A challenge here is - what to do on navigation from child to parent, but it could be done by moving that setting into controller and work with $scope.$on('detsroy'...

Here is adjusted plunker

.state('parent.child', { 
      url: "/child",
      templateUrl: 'tpl.html',
      controller: 'ChildCtrl',
      // no resolve, just controller fills the target
  })

.controller('ChildCtrl', ['$rootScope', '$scope', function ($rootScope, $scope) { 
  var title = $rootScope.title;
  $rootScope.title = "Title from Child";
  $scope.$on('$destroy', function(){$rootScope.title = title});
}])


来源:https://stackoverflow.com/questions/33466662/angular-ui-router-title-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!