基于条件的控制器路由angularjs

时间:2017-12-15 07:08:28

标签: javascript angularjs

我想传递一个隐藏值或一些不属于URL的可选参数,以便在基于param的状态之间进行更改。所以我尝试了

<a ui-sref="state2({key:'value', optional: 'B'})">Send param and go to page 2</a>

在路线提供者

$stateProvider
  .state('state2', {
  url: "/:key",
  templateUrl: "state1.html",
  params: {
    optional: null
  },
  controller: 'contollerA'
})
  .state('state3', {
  url: "/:key",
  templateUrl: "state3.html",
  controller: 'contollerB'
})
  .state('state4', {
  url: "/:key",
  templateUrl: "state4.html",
  controller: 'contollerC'
})

在控制器中

.controller('contollerA', function($scope, $stateParams, $state) {
    if ($stateParams.optional === 'B') {
        $state.go('state3');
    } else {
        $state.go('state4');
    }
})

但是这不能像浏览器控制台上显示的错误一样

无效的州参考

实现这个目标的方法是什么?

1 个答案:

答案 0 :(得分:0)

因为state2不包含param&#34; key&#34;在配置中。取代

.state('state2', {
  url: "/:key",
  templateUrl: "state1.html",
  params: {
     optional: null
  },
 controller: 'contollerA'
})

.state('state2', {
  url: "/:key?optional",
  templateUrl: "state1.html",
  params: {
     optional: null,
     key: null
  },
 controller: 'contollerA'
})