【问题标题】:How get $state with absolute URL in Angular如何在 Angular 中使用绝对 URL 获取 $state
【发布时间】:2016-02-26 21:07:05
【问题描述】:

我正在尝试获取 URL$state

基本上我想做 reverse 的:

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

我想获取州名,而不是 Abs URL

我想将 Abs URL 传递给函数,然后在 Angular 的项目中获取有效的$state

【问题讨论】:

  • 如有疑问...console.log($state) 并检查那里有什么
  • 检查更新的答案是否对您有所帮助。不完全是您想要的,但可能满足您的需要。

标签: angularjs angular-ui-router


【解决方案1】:

有一个名为$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);
    });

【讨论】:

  • 刚刚更新了问题...我想传递一个 URL 并在应用程序中获取一个有效的 $state...这可能吗?
  • 我不知道,因为文档没有提到你现在所期望的。我们正在谈论可能会或可能不会解析为状态的 absURL。不过可能会有一些黑客攻击。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
相关资源
最近更新 更多