我可以动态设置ui-router状态的数据属性吗?

时间:2017-02-19 12:07:25

标签: angularjs angular-ui-router state router

想象一下,我有一个像这样的状态定义:

$stateProvider.state("main", {
   url: "main/:param/list",
   controller: "MainController",
   data: function($stateParams) {
      if($stateParams.param === "A") {
         return 'param1';
      } else if($stateParams.param === "B") {
         return 'param2';
      }
   }
}

我可以像这样设置数据属性吗?有没有办法达到预期的行为?

1 个答案:

答案 0 :(得分:1)

数据对象是您要添加到$ state服务的任何数据的存储,这意味着您可以将该函数存储在其中,但是您不会执行它,我认为不是您要尝试的实现,您可以了解如何将自定义数据添加到$ state here ,所以要做你想做的逻辑,你必须使用控制器而不是$ state服务,如下所示:

$stateProvider.state("main", {
 url: "main/:param/list",
 controller: "MainController"/*,
 //only if you want to "store" your data on the $state, u can use it like this
 data: {
  myCustomParam: 'my Awesome Value'
 }*/
})//..all your other states

//now you pass the parameter in the url like This
//http://xxxxxxx/main/myparamvalue/list
//and in the controller
app.controller('MainController',function($state, $stateParams){
  //Here you do your Logic
  if($stateParams.param === "myparamvalue") {
     console.log('param1');//it should go here
  } else if($stateParams.param === "anythingelse") {
     console.log('param2');
  }
  /*if you have any values to get from the state data as previously mentioned you can get it like this*/
  console.log($state.current.data.myCustomParam);//output: my Awesome Value

});