使用angular-ui-router

时间:2017-03-01 08:32:06

标签: javascript angularjs angular-ui-router

我的应用程序的入口点是一个参数值未知的URL,例如:

http://www.host.com/key/25

我的简化配置如下:

$stateProvider.state('home', {
        url: "/key/:key",
        component: 'home'
}).state('sitenotice', {
        url: "/sitenotice/",
        component: 'sitenotice'
});

我尝试导航到“sitenotice”并返回到index.html中的“main”:

<html ng-app="myApp">
  ...
  <div ui-view></div>

  <a ui-sref="sitenotice">site notice</a>
  <a ui-sref="home">home</a>
</html>

它不起作用,因为我没有将key-Parameter传递给状态“home”。我不知道如何访问初始值。或者它可以以某种方式缓存?是否有可能只使用ui-router,我还没有使用根控制器。

我使用angular 1.5.8和angular-ui-router 1.0.0-beta.3。

1 个答案:

答案 0 :(得分:0)

我的解决方案是使用rootScope并在那里存储参数值。我还对angular-ui-router 1.0.0-rc.1进行了更新。离开“home”状态时,$ rootScope.navKey获取当前状态参数值。

angular
.module('myApp')
.run(function ($rootScope, $stateParams, $transitions) {
  $rootScope.navKey = "";

  $transitions.onExit({ exiting: 'home' }, function() {
    if (angular.isDefined($stateParams.key)) {
        $rootScope.navKey = $stateParams.key;
    }
  });
});

在我的index.html中,我使用navKey返回“main”-state:

<a ui-sref="home({ key: navKey })">
  <md-button md-no-ink="" class="md-primary">Home</md-button>
</a>