如何使用Angularjs ui-router和组件传递不在URL中的参数?

时间:2018-01-25 18:19:34

标签: angularjs angular-ui-router

我无法弄清楚如何使用angularjs ui-router传递参数,因为$stateParams在ui-router 1.x中已经depricated。 ui-router文档显示了通过URL传递参数的example,但没有传递未包含在URL中的参数的示例。

{
  name: 'person',
  url: '/people/{personId}',
  component: 'person',
  resolve: {
    person: function(PeopleService, $transition$) {
      return PeopleService.getPerson($transition$.params().personId);
    }
  }
}

以前通过向状态对象添加params对象使用$stateParamspossible

.state('contacts', {
        url: "/contacts",
        params: {
            param1: null
        },
        templateUrl: 'contacts.html'
    })

但是,这需要现已弃用的$stateParams

我尝试过混合使用这两种方法,但是我无法让它工作。

{
  name: 'person',
  url: '/people/',
  component: 'person',
  params:{
    personId:null
  }
  resolve: {
    person: function(PeopleService, $transition$) {
      return PeopleService.getPerson($transition$.params().personId);
    }
  }
}

此功能是否已从ui-router中删除?是否有更好的方法来传递参数,尤其是对象,而不会制作荒谬的URL?

1 个答案:

答案 0 :(得分:0)

我发现参数是通过$transition$对象传递的。但是,此对象不像常规提供程序那样传递给控制器​​。您通过组件上的绑定传递$transition$对象。 $transition$会自动绑定here

ui-router配置:

.state({
        name: "contacts",
        url: "/contacts",
        params: {
            param1: null
        },
        component: "contacts"
    })

控制器:

module.component("contacts", {
    bindings: { 
        $transition$: '<'
    },
    controller: {
        var $ctrl = this;

        $ctrl.$onInit = function(){
            var param1 = $ctrl.$transition$.params().param1;
        };
    }
}

HTML链接

<a ui-sref="contacts({param1:$ctrl.myParam})" ui-sref-active="active">Contacts</a>

有关使用$transition$$transition$.params()的更多信息,请访问ui-router's Github page