为动态标题返回$ stateParams

时间:2016-05-06 19:57:23

标签: javascript angularjs angular-ui-router angular-ui

点击指向“计数”页面的链接

后,我可以传递路由器参数
<form [...]> 
  <input type="text" id="name" name="name" required="required" placeholder="Name" minlength="2" />
  <input type="email" id="email" name="email" required="required" placeholder="Email" />  
  <input name="submit" type="submit" title="Submit" class="submit_go" value="Submit" />
</form>

由于路由器中建立的内容如下所示:

$state.go('count', {targetName: object.name})

我们正在使用UI-Router中的url: '/count/:targetName', 选项与data:一起动态设置我们的页面标题

$state

我希望<title ng-bind="'Application Name : ' + $state.current.data.pageTitle"></title> 包含pageTitle。所以为了做到这一点,我相信我需要在路由器的:targetName属性中设置一个函数。我尝试过这样的事情:

data:

这根本不允许页面解析。

任何提示?

1 个答案:

答案 0 :(得分:2)

a working plunker

让我们拥有这些状态

// this is just a state, with its own pageTitle STRING
.state('home', {
    ...
    data: {
       pageTitle: "Just a home page"
    },
})
// this is a parent state, with URL parameter 'someParam'
// nad pageTitle as a function
.state('parent', {
    ...
    url: "/parent?someParam",
    data: {
        pageTitle: function ($stateParams) {
          return `title with a param ${$stateParams.someParam}`;
        }
    }
})
// and to show that child can change it
.state('parent.child', { 
    ...
    data: {
        pageTitle: "just a child title",
    }
})

使这行代码正常工作:

<title>The tile is: {{ getTitle() }}  </title>

我们可以在$rootScope添加小评价,但当然,它应该是一些服务...... 将其作为简化的方法

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

    $rootScope.getTitle = function(){
      var state = $state.current;
      var params = $stateParams;

      if (state.data
      && state.data.pageTitle) {

        if(typeof (state.data.pageTitle) === "function" ){
          return state.data.pageTitle(params);
        }
        return state.data.pageTitle
      }
      return "no title for this state"
    }
}])

并且所有这些链接都有不同的标题

<a href="#/home">
<a ui-sref="parent({someParam: 1})">
<a ui-sref="parent({someParam: 'someValue'})">
<a ui-sref="parent.child">

检查行动here