为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

白衣染霜花 2019-11-25 15:18:45
我正在将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
查看完整描述

3 回答

?
饮歌长啸

TA贡献1951条经验 获得超3个赞

如果要传递非URL状态,则url在设置时一定不要使用state。我在PR上找到了答案,并四处游逛以更好地理解。


$stateProvider.state('toState', {

  templateUrl:'wokka.html',

  controller:'stateController',

  params: {

    'referer': 'some default', 

    'param2': 'some default', 

    'etc': 'some default'

  }

});

然后,您可以像这样导航到它:


$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的情况下转换状态的有效方法。


查看完整回答
反对 回复 2019-11-25
?
浮云间

TA贡献1829条经验 获得超3个赞

内森·马修斯(Nathan Matthews)的解决方案对我不起作用,但这是完全正确的,但没有解决之道:


关键点是:$ state.go的已定义参数和toParamas的类型在状态转换的两侧应为相同的数组或对象。


例如,当您按如下所示在状态中定义参数时,则表示参数是数组,因为使用了[[]]:


$stateProvider

.state('home', {

    templateUrl: 'home',

    controller:  'homeController'

})

.state('view', {

    templateUrl: 'overview',

    params:      ['index', 'anotherKey'],

    controller:  '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) {

    var index = $stateParams[0];

    var anotherKey = $stateParams[1];

});

更好的解决方案是在两侧都使用对象而不是数组:


$stateProvider

.state('home', {

    templateUrl: 'home',

    controller:  'homeController'

})

.state('view', {

    templateUrl: 'overview',

    params:      {'index': null, 'anotherKey': null},

    controller:  'overviewController'

})

我在参数定义中将{]替换为{}。为了将toParams传递给$ state.go,您还应该使用object而不是array:


$state.go('view', { 'index': 123, 'anotherKey': 'This is a test' })

那么您可以通过$ stateParams轻松访问它们:


app.controller('overviewController', function($scope, $stateParams) {

    var index = $stateParams.index;

    var anotherKey = $stateParams.anotherKey;

});


查看完整回答
反对 回复 2019-11-25
  • 3 回答
  • 0 关注
  • 851 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信