UI 路由器动态<title>标记



我正在为UI-Router中的每个状态添加标题:

.state('projects', {
    url: '/',
    templateUrl: 'projects/projects.html',
    ncyBreadcrumb: {
        label: 'Projects'
    },
    data : {title: 'Projects'}
})

,然后标题属性获取该数据:

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

如何从状态参数中获取数据并将其添加到上面示例中的标题中?我尝试以下没有运气:

.state('project', {
    abstract: true,
    url: '/projects/:projId',
    resolve:{
        projId: ['$stateParams', function($stateParams){
            return $stateParams.projId;
        }]
    },
    controller: 'projectCtrl',
    templateUrl: 'project/project.html',
    ncyBreadcrumb: {
        label: 'Project',
        parent: 'projects'
    },
    data : {title: '{{state}}'}
}) 

您必须在app.js文件中使用 app.run(),然后在 $ rototscope.title 中分配标题。您可以遵循此代码

app.run(function($rootScope){
    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState){
        $rootScope.title=toState.data.title;
    });
});

之后,然后像这样绑定html中的变量

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

我认为这会有所帮助

有一个工作示例

我会说,你快到了。标题看起来像这样:

<title>{{$state.current.data.title}} {{$stateParams.ID}}</title>

让我们有这两个状态:

  .state('parent', {
      url: "/parent",
      templateUrl: 'tpl.html',
      data : { title: 'Title for PARENT' },
  })
  .state('parent.child', { 
      url: "/child/:ID",
      templateUrl: 'tpl.html',
      controller: 'ChildCtrl',
      data : { title: 'Title for CHILD' },
  })
  ;

这样称呼它们:

<a ui-sref="parent">
<a ui-sref="parent.child({ID:1})">
<a ui-sref="parent.child({ID:2})">

和此钩子:

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

因此,关键是,在$rootScope中,我们可以访问 $state.current $stateParams

在此处检查它(注意,要在分离的窗口中查看Plunker,单击右 - 顶角蓝色图标 - 新窗口也将更改标题)

我建议您使用参数选项而不是使用data选项,因为参数可以是可选的,您可以通过在$state.goui-sref指令中传递参数来动态设置它。

代码

.state('projects', {
    url: '/',
    templateUrl: 'projects/projects.html',
    ncyBreadcrumb: {
        label: 'Projects'
    },
    params: {
        title: { value: null }
    }
});

来自控制器

$state.go('projects', {title: 'Page1'}); //you can change title while calling state

来自html

ui-sref="projects({title: 'Something Else'})"

最新更新