AngularJS + UI-Router:查看href或ui-sref是否与状态匹配

And*_*lin 5 angularjs angular-ui-router

所以目前,我正在使用UI-Router来管理一组tab指令.通过标签,我的意思是这个UI范例:http: //www.hollance.com/wp-content/uploads/2011/11/Screenshot.png

每个选项卡都可以包含a title,an icon和a hrefui-sref与之关联.

例:

<my-tabs>
  <my-tab title="Tab 1" href="#/tab1">
    Content when tab 1 is active!
  </my-tab>
  <my-tab title="Tab 2" ui-sref="tabs.numberTwo()">
    Content when tab 2 is active!
  </my-tab>
</my-tabs>
Run Code Online (Sandbox Code Playgroud)

无论如何,主要问题是当以编程方式或通过浏览器刷新更改状态时,我希望能够根据或属性知道要选择哪个选项卡. 似乎没有做我需要的东西:我不能给它并询问它是否与当前状态匹配 - 我也不能给它一个ui-sref.ui-srefhref$state.(is|includes|contains)$state.ishref

我也可以stateName在选项卡中添加属性等,但如果我不需要,我宁愿不这样做.

基本上,我希望能够在tab指令中执行此操作:

$rootScope.$on('$stateChangeSuccess', function() {
   if ($state.matchesHref(attrs.href) || $state.matchesSref(attrs.uiSref)) {
    selectThisTab();
  }
});
Run Code Online (Sandbox Code Playgroud)

任何想做这件事的想法都会受到欢迎!

And*_*lin 3

所以我终于让它工作了,谢谢大家。

我检查 $location.href() 中的 attrs.href,并拆分 sref 以获取 attrs.uiSref 的 stateName。

这种分割并不理想,但这是我现在能找到的最好的分割。

$rootScope.$on('$stateChangeSuccess', selectTabIfMatchesState);
function selectTabIfMatchesState() {
  //get rid of leading # if it exists, to match against $location.path()
  var href = $attr.href && $attr.href.replace(/^#/, '');

  //uiSref is laid out as 'stateName({params})', get only 'stateName'
  var stateName = $attr.uiSref && $attr.uiSref.split('(')[0];

  var includesState = stateName && $state.includes(stateName);
  var includesHref = href && $location.path().indexOf(href) === 0;

  if (includesHref || includesState) {
    // this tab matches current state, go to it!
    tabsCtrl.select($scope);
  }
}
Run Code Online (Sandbox Code Playgroud)