如何使用$ state.go toParams和$ stateParams发送和检索参数?

我正在将AngularJS v1.2.0-rc.2与ui-router v0.2.0一起使用。我想将引荐来源网址状态传递给另一个状态,因此我使用的toParams方式$state.go如下:


$state.go('toState', {referer: $state.current.name});

根据文档,这应该填充控制器$stateParams上的toState,但是它是undefined。我想念什么?


我创建了一个小例子来演示:


http://plnkr.co/edit/ywEcG1


白衣染霜花
浏览 857回答 3
3回答

饮歌长啸

如果要传递非URL状态,则url在设置时一定不要使用state。我在PR上找到了答案,并四处游逛以更好地理解。$stateProvider.state('toState', {&nbsp; templateUrl:'wokka.html',&nbsp; controller:'stateController',&nbsp; params: {&nbsp; &nbsp; 'referer': 'some default',&nbsp;&nbsp; &nbsp; 'param2': 'some default',&nbsp;&nbsp; &nbsp; 'etc': 'some default'&nbsp; }});然后,您可以像这样导航到它:$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });要么:var result = { referer:'jimbob', param2:37, etc:'bluebell' };$state.go('toState', result);因此,在HTML中:<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>该用例已在文档中完全揭露,但是我认为这是在不使用URL的情况下转换状态的有效方法。

浮云间

内森·马修斯(Nathan Matthews)的解决方案对我不起作用,但这是完全正确的,但没有解决之道:关键点是:$ state.go的已定义参数和toParamas的类型在状态转换的两侧应为相同的数组或对象。例如,当您按如下所示在状态中定义参数时,则表示参数是数组,因为使用了[[]]:$stateProvider.state('home', {&nbsp; &nbsp; templateUrl: 'home',&nbsp; &nbsp; controller:&nbsp; 'homeController'}).state('view', {&nbsp; &nbsp; templateUrl: 'overview',&nbsp; &nbsp; params:&nbsp; &nbsp; &nbsp; ['index', 'anotherKey'],&nbsp; &nbsp; controller:&nbsp; 'overviewController'})因此,您也应该像这样将toParams作为数组传递:params = { 'index': 123, 'anotherKey': 'This is a test' }paramsArr = (val for key, val of params)$state.go('view', paramsArr)您可以通过$ stateParams作为数组访问它们,如下所示:app.controller('overviewController', function($scope, $stateParams) {&nbsp; &nbsp; var index = $stateParams[0];&nbsp; &nbsp; var anotherKey = $stateParams[1];});更好的解决方案是在两侧都使用对象而不是数组:$stateProvider.state('home', {&nbsp; &nbsp; templateUrl: 'home',&nbsp; &nbsp; controller:&nbsp; 'homeController'}).state('view', {&nbsp; &nbsp; templateUrl: 'overview',&nbsp; &nbsp; params:&nbsp; &nbsp; &nbsp; {'index': null, 'anotherKey': null},&nbsp; &nbsp; controller:&nbsp; 'overviewController'})我在参数定义中将{]替换为{}。为了将toParams传递给$ state.go,您还应该使用object而不是array:$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })那么您可以通过$ stateParams轻松访问它们:app.controller('overviewController', function($scope, $stateParams) {&nbsp; &nbsp; var index = $stateParams.index;&nbsp; &nbsp; var anotherKey = $stateParams.anotherKey;});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

AngularJS