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

can I set ui-router state's data attribute dynamically?

假设我有这样一个状态定义:

$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';
      }
   }
}

我可以这样设置数据属性吗?有什么方法可以达到预期的效果吗?

数据对象是你想要添加到 $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

});