如何在Angular中使用绝对URL获取$ state

时间:2016-02-26 21:07:06

标签: angularjs angular-ui-router

我试图获取网址<{strong>的$state

基本上我想做反向

$state.href('user.home.view', {}, {absolute: true});

而不是获取Abs URL我想获得州名称

我想将 Abs网址传递给某个函数,然后在角度项目中获得有效的$state

1 个答案:

答案 0 :(得分:2)

有一个名为$uiView的数据字段附加到ui-view元素,它包含视图名称和关联状态。你可以得到这样的状态:

elem.closest('[ui-view]').data('$uiView').state

甚至

elem.inheritedData('$uiView').state

所以,在你的控制器中:

 .controller('State1Ctrl', function ($state) {
      console.log(elem.closest('[ui-view]').data('$uiView').state); // state1
      console.log($state.current.name)  ;//will give the state name as well.  
});  

<强>更新

Your issue: https://github.com/angular-ui/ui-router/issues/1651

解决方法:
ANGULAR-UI-ROUTER: Resolve state from URL

您可以使用$stateProvider上的.decorator挂钩公开内部状态实现。你可以装饰国家建设者的任何财产;有人随意选择了'parent'

app.config(function($stateProvider) { 
  $stateProvider.decorator('parent', function (internalStateObj, parentFn) {
     // This fn is called by StateBuilder each time a state is registered

     // The first arg is the internal state. Capture it and add an accessor to public state object.
     internalStateObj.self.$$state = function() { return internalStateObj; };

     // pass through to default .parent() function
     return parentFn(internalStateObj); 
  });
});

现在,您可以使用。$$ state(),例如

来访问内部状态对象
var publicState = $state.get("foo");
    var privateInternalState = publicState.$$state();
    //Second, loop over each state in $state.get() and test them against your URL fragment.

    angular.forEach($state.get(), function(state) { 
      var privatePortion = state.$$state();
      var match = privatePortion.url.exec(url, queryParams);
      if (match) console.log("Matched state: " + state.name + " and parameters: " + match);
    });