如何使用$state发送和检索参数。去toParams stateParams美元吗?

时间:2021-12-04 11:38:59

I am using AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I want to pass the referrer state to another state so I use the toParams of $state.go like so:

我正在使用AngularJS v1.2.0-rc。2与ui-router v0.2.0。我想将referrer状态传递到另一个状态,因此使用$state的toParams。像这样:

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

According to the docs, this should populate the $stateParams on the toState controller, but it is undefined. What am I missing?

根据文档,这应该在toState控制器上填充$stateParams,但是它是未定义的。我缺少什么?

I've created a plunk to demonstrate:

我创造了一个扑通一声来证明:

http://plnkr.co/edit/ywEcG1

http://plnkr.co/edit/ywEcG1

12 个解决方案

#1


139  

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

如果您希望传递非url状态,那么在设置状态时必须不使用url。我在公共关系上找到了答案,为了更好地理解它,我到处胡闹。

$stateProvider.state('toState', {
  templateUrl:'wokka.html',
  controller:'stateController',
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'
  }
});

Then you can navigate to it like so:

然后你可以这样导航到它:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });

Or:

或者:

var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

在HTML这样:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.

这个用例在文档中已经完全暴露出来了,但是我认为这是在不使用url的情况下进行状态转换的一种强大方法。

#2


44  

The Nathan Matthews's solution did not work for me but it is totally correct but there is little point to reaching a workaround:

Nathan Matthews的解决方案对我不起作用,但它是完全正确的,但是找到一个解决方案是没有意义的:

The key point is: Type of defined parameters and toParamas of $state.go should be same array or object on both sides of state transition.

关键是:定义参数的类型和$state的toParamas。go应该是状态转换两边的相同数组或对象。

For example when you define a params in a state as follows you means params is array because of using "[]":

例如,当您在如下状态下定义params时,您的意思是params是数组,因为使用了"[]":

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      ['index', 'anotherKey'],
    controller:  'overviewController'
})

So also you should pass toParams as array like this:

所以你也应该像这样传递toParams数组:

params = { 'index': 123, 'anotherKey': 'This is a test' }
paramsArr = (val for key, val of params)
$state.go('view', paramsArr)

And you can access them via $stateParams as array like this:

你可以通过$stateParams作为数组访问它们:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams[0];
    var anotherKey = $stateParams[1];
});

Better solution is using object instead of array in both sides:

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

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      {'index': null, 'anotherKey': null},
    controller:  'overviewController'
})

I replaced [] with {} in params definition. For passing toParams to $state.go also you should using object instead of array:

我用params定义中的{}替换了[]。将toParams传送到$state。你也应该使用对象而不是数组:

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

then you can access them via $stateParams easily:

然后您可以通过$stateParams轻松访问它们:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

#3


26  

All I had to do was add a parameter to the url state definition like so

我所要做的就是向url状态定义添加一个参数

url: '/toState?referer'

Doh!

哎!

#4


15  

Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.

不确定它是否适用于AngularJS v1.2.0-rc。2与ui-router v0.2.0。我在AngularJS v1.3.14和ui-路由器v0.2.13上测试了这个解决方案。

I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.

我只是意识到,不需要按照gwhn的建议在URL中传递参数。

Just add your parameters with a default value on your state definition. Your state can still have an Url value.

只需在状态定义上添加具有默认值的参数。您的状态仍然可以有一个Url值。

$stateProvider.state('state1', {
    url : '/url',
    templateUrl : "new.html",
    controller : 'TestController',
    params: {new_param: null}
});

and add the param to $state.go()

并将参数添加到$state。go()

$state.go('state1',{new_param: "Going places!"});

#5


14  

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

这一页上的这些例子都不适合我。这是我用过的,效果很好。有些解决方案说不能将url与$state.go()合并,但这不是事实。令人尴尬的是,您必须为url定义params,并列出params。都必须存在。测试角度1.4.8和UI路由器0.2.15。

In the state add your params to end of state and define the params:

在状态中添加您的参数以结束状态并定义参数:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

在控制器中,go语句将如下所示:

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

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

然后将params取出,并在新状态的控制器中使用它们(不要忘记向控制器函数传递$stateParams):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

#6


8  

I've spent a good deal of time fighting with Ionic / Angular's $state & $stateParams;

我花了很多时间和离子/角的$state & $stateParams斗争;

To utilize $state.go() and $stateParams you must have certain things setup and other parameters must not be present.

要使用$state.go()和$stateParams,您必须设置某些东西,并且其他参数不能出现。

In my app.config() I've included $stateProvider and defined within it several states:

在我的app.config()中,我包含了$stateProvider,并在其中定义了几个状态:

$stateProvider
    .state('home', {
        templateUrl: 'home',
        controller:  'homeController'
    })
    .state('view', {
        templateUrl: 'overview',
        params:      ['index', 'anotherKey'],
        controller:  'overviewController'
    })

The params key is especially important. As well, notice there are NO url keys present... utilizing stateParams and URLs do NOT mix. They are mutually exclusive to each other.

params键特别重要。同样,注意这里没有url键……使用状态参数和url不会混合。它们相互排斥。

In the $state.go() call, define it as such:

在$state.go()调用中,将其定义为:

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

The index and anotherKey $stateParams variables will ONLY be populated if they are first listed in the $stateController params defining key.

索引和其他关键$stateParams变量只会在$stateController params定义键中首次列出时才会填充。

Within the controller, include $stateParams as illustrated:

在控制器内,包括$stateParams,如图所示:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

The passed variables should be available!

所传递的变量应该是可用的!

#7


8  

In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:

在我的例子中,我尝试了这里给出的所有选项,但是没有人能正常工作(角度1.3.13,离子1.0.0,角度-ui-路由器0.2.13)。解决方案是:

.state('tab.friends', {
      url: '/friends/:param1/:param2',
      views: {
        'tab-friends': {
          templateUrl: 'templates/tab-friends.html',
          controller: 'FriendsCtrl'
        }
      }
    })

and in the state.go:

和state.go:

$state.go('tab.friends', {param1 : val1, param2 : val2});

Cheers

干杯

#8


5  

Try With reload: true?

Couldn't figure out what was going on for the longest time -- turns out I was fooling myself. If you're certain that things are written correctly and you will to use the same state, try reload: true:

长时间搞不清到底是怎么回事——原来我是在欺骗自己。如果你确定写的东西是正确的,并且你将使用相同的状态,请尝试重载:true:

.state('status.item', {
    url: '/:id',
    views: {...}
}

$state.go('status.item', { id: $scope.id }, { reload: true });

Hope this saves you time!

希望这能节省你的时间!

#9


4  

I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.

我也遇到过类似的问题。经过大量的搜索、试验和测试,我最终找到了一个可行的解决方案。这是我的解决办法,对你有用。

I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:

我有两个控制器——searchBoxController和stateResultController,以及一个名为searchQuery的参数,将从具有搜索框的视图传递到显示从远程服务器获取的结果的视图。你就是这样做的:

Below is the controller from which you call the next view using $state.go()

下面是使用$state调用下一个视图的控制器。go()

.controller('searchBoxController', function ($scope, $state) {
        $scope.doSearch = function(){
            var searchInputRaw = $scope.searchQueryInput;
            $state.go('app.searchResults', { searchQuery: searchInput });
        }
    })

Below is the state that would be called when the $state.go() gets executed:

下面是执行$state.go()时将调用的状态:

.state('app.searchResults', 
            {
                url: '/searchResults',
                views:
                {
                    'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
                },
                params: 
                {
                    'searchQuery': ''
                }
            })

And finally, the controller associated with the app.searchResults state:

最后,与app.searchResults状态相关联的控制器:

.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
        $scope.searchQueryInput = $stateParams.searchQuery;
    });

#10


3  

And in my case of a parent/child state. all the parameters declared in child state has to be known by the parent state

对于父/子状态。子状态中声明的所有参数必须由父状态知道

        .state('full', {
            url: '/full',
            templateUrl: 'js/content/templates/FullReadView.html',
            params: { opmlFeed:null, source:null },
            controller: 'FullReadCtrl'
        })
        .state('full.readFeed', {
            url: '/readFeed',
            views: {
                'full': {
                    templateUrl: 'js/content/templates/ReadFeedView.html',
                    params: { opmlFeed:null, source:null },
                    controller: 'ReadFeedCtrl'
                }
            }
        })

#11


2  

The solution we came to having a state that took 2 parameters was changing:

我们得到的结果是有两个参数的状态在改变:

.state('somestate', {
  url: '/somestate',
  views: {...}
}

to

.state('somestate', {
  url: '/somestate?id=:&sub=:',
  views: {...}
}

#12


0  

If this is a query parameter that you want to pass like this: /toState?referer=current_user

如果要传递的查询参数是:/toState?referer=current_user

then you need to describe your state like this:

然后你需要这样描述你的状态:

$stateProvider.state('toState', {
  url:'toState?referer',
  views:{'...'}
});

source: https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters

来源:https://github.com/angular-ui/ui-router/wiki/URL-Routing查询参数

#1


139  

If you want to pass non-URL state, then you must not use url when setting up your state. I found the answer on a PR and did some monkeying around to better understand.

如果您希望传递非url状态,那么在设置状态时必须不使用url。我在公共关系上找到了答案,为了更好地理解它,我到处胡闹。

$stateProvider.state('toState', {
  templateUrl:'wokka.html',
  controller:'stateController',
  params: {
    'referer': 'some default', 
    'param2': 'some default', 
    'etc': 'some default'
  }
});

Then you can navigate to it like so:

然后你可以这样导航到它:

$state.go('toState', { 'referer':'jimbob', 'param2':37, 'etc':'bluebell' });

Or:

或者:

var result = { referer:'jimbob', param2:37, etc:'bluebell' };
$state.go('toState', result);

And in HTML thusly:

在HTML这样:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

This use case is completely uncovered in the documentation, but I think it's a powerful means on transitioning state without using URLs.

这个用例在文档中已经完全暴露出来了,但是我认为这是在不使用url的情况下进行状态转换的一种强大方法。

#2


44  

The Nathan Matthews's solution did not work for me but it is totally correct but there is little point to reaching a workaround:

Nathan Matthews的解决方案对我不起作用,但它是完全正确的,但是找到一个解决方案是没有意义的:

The key point is: Type of defined parameters and toParamas of $state.go should be same array or object on both sides of state transition.

关键是:定义参数的类型和$state的toParamas。go应该是状态转换两边的相同数组或对象。

For example when you define a params in a state as follows you means params is array because of using "[]":

例如,当您在如下状态下定义params时,您的意思是params是数组,因为使用了"[]":

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      ['index', 'anotherKey'],
    controller:  'overviewController'
})

So also you should pass toParams as array like this:

所以你也应该像这样传递toParams数组:

params = { 'index': 123, 'anotherKey': 'This is a test' }
paramsArr = (val for key, val of params)
$state.go('view', paramsArr)

And you can access them via $stateParams as array like this:

你可以通过$stateParams作为数组访问它们:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams[0];
    var anotherKey = $stateParams[1];
});

Better solution is using object instead of array in both sides:

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

$stateProvider
.state('home', {
    templateUrl: 'home',
    controller:  'homeController'
})
.state('view', {
    templateUrl: 'overview',
    params:      {'index': null, 'anotherKey': null},
    controller:  'overviewController'
})

I replaced [] with {} in params definition. For passing toParams to $state.go also you should using object instead of array:

我用params定义中的{}替换了[]。将toParams传送到$state。你也应该使用对象而不是数组:

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

then you can access them via $stateParams easily:

然后您可以通过$stateParams轻松访问它们:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

#3


26  

All I had to do was add a parameter to the url state definition like so

我所要做的就是向url状态定义添加一个参数

url: '/toState?referer'

Doh!

哎!

#4


15  

Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.

不确定它是否适用于AngularJS v1.2.0-rc。2与ui-router v0.2.0。我在AngularJS v1.3.14和ui-路由器v0.2.13上测试了这个解决方案。

I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.

我只是意识到,不需要按照gwhn的建议在URL中传递参数。

Just add your parameters with a default value on your state definition. Your state can still have an Url value.

只需在状态定义上添加具有默认值的参数。您的状态仍然可以有一个Url值。

$stateProvider.state('state1', {
    url : '/url',
    templateUrl : "new.html",
    controller : 'TestController',
    params: {new_param: null}
});

and add the param to $state.go()

并将参数添加到$state。go()

$state.go('state1',{new_param: "Going places!"});

#5


14  

None of these examples on this page worked for me. This is what I used and it worked well. Some solutions said you cannot combine url with $state.go() but this is not true. The awkward thing is you must define the params for the url and also list the params. Both must be present. Tested on Angular 1.4.8 and UI Router 0.2.15.

这一页上的这些例子都不适合我。这是我用过的,效果很好。有些解决方案说不能将url与$state.go()合并,但这不是事实。令人尴尬的是,您必须为url定义params,并列出params。都必须存在。测试角度1.4.8和UI路由器0.2.15。

In the state add your params to end of state and define the params:

在状态中添加您的参数以结束状态并定义参数:

url: 'view?index&anotherKey',
params: {'index': null, 'anotherKey': null}

In your controller your go statement will look like this:

在控制器中,go语句将如下所示:

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

Then to pull the params out and use them in your new state's controller (don't forget to pass in $stateParams to your controller function):

然后将params取出,并在新状态的控制器中使用它们(不要忘记向控制器函数传递$stateParams):

var index = $stateParams.index;
var anotherKey = $stateParams.anotherKey;
console.log(anotherKey); //it works!

#6


8  

I've spent a good deal of time fighting with Ionic / Angular's $state & $stateParams;

我花了很多时间和离子/角的$state & $stateParams斗争;

To utilize $state.go() and $stateParams you must have certain things setup and other parameters must not be present.

要使用$state.go()和$stateParams,您必须设置某些东西,并且其他参数不能出现。

In my app.config() I've included $stateProvider and defined within it several states:

在我的app.config()中,我包含了$stateProvider,并在其中定义了几个状态:

$stateProvider
    .state('home', {
        templateUrl: 'home',
        controller:  'homeController'
    })
    .state('view', {
        templateUrl: 'overview',
        params:      ['index', 'anotherKey'],
        controller:  'overviewController'
    })

The params key is especially important. As well, notice there are NO url keys present... utilizing stateParams and URLs do NOT mix. They are mutually exclusive to each other.

params键特别重要。同样,注意这里没有url键……使用状态参数和url不会混合。它们相互排斥。

In the $state.go() call, define it as such:

在$state.go()调用中,将其定义为:

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

The index and anotherKey $stateParams variables will ONLY be populated if they are first listed in the $stateController params defining key.

索引和其他关键$stateParams变量只会在$stateController params定义键中首次列出时才会填充。

Within the controller, include $stateParams as illustrated:

在控制器内,包括$stateParams,如图所示:

app.controller('overviewController', function($scope, $stateParams) {
    var index = $stateParams.index;
    var anotherKey = $stateParams.anotherKey;
});

The passed variables should be available!

所传递的变量应该是可用的!

#7


8  

In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:

在我的例子中,我尝试了这里给出的所有选项,但是没有人能正常工作(角度1.3.13,离子1.0.0,角度-ui-路由器0.2.13)。解决方案是:

.state('tab.friends', {
      url: '/friends/:param1/:param2',
      views: {
        'tab-friends': {
          templateUrl: 'templates/tab-friends.html',
          controller: 'FriendsCtrl'
        }
      }
    })

and in the state.go:

和state.go:

$state.go('tab.friends', {param1 : val1, param2 : val2});

Cheers

干杯

#8


5  

Try With reload: true?

Couldn't figure out what was going on for the longest time -- turns out I was fooling myself. If you're certain that things are written correctly and you will to use the same state, try reload: true:

长时间搞不清到底是怎么回事——原来我是在欺骗自己。如果你确定写的东西是正确的,并且你将使用相同的状态,请尝试重载:true:

.state('status.item', {
    url: '/:id',
    views: {...}
}

$state.go('status.item', { id: $scope.id }, { reload: true });

Hope this saves you time!

希望这能节省你的时间!

#9


4  

I'd faced a similar problem. I ended up with a working solution after a lot of googling and trial and test. Here is my solution which would work for you.

我也遇到过类似的问题。经过大量的搜索、试验和测试,我最终找到了一个可行的解决方案。这是我的解决办法,对你有用。

I have two controllers - searchBoxController and stateResultController and a parameter named searchQuery to be passed from a view having a search box to a view showing the results fetched from a remote server. This is how you do it:

我有两个控制器——searchBoxController和stateResultController,以及一个名为searchQuery的参数,将从具有搜索框的视图传递到显示从远程服务器获取的结果的视图。你就是这样做的:

Below is the controller from which you call the next view using $state.go()

下面是使用$state调用下一个视图的控制器。go()

.controller('searchBoxController', function ($scope, $state) {
        $scope.doSearch = function(){
            var searchInputRaw = $scope.searchQueryInput;
            $state.go('app.searchResults', { searchQuery: searchInput });
        }
    })

Below is the state that would be called when the $state.go() gets executed:

下面是执行$state.go()时将调用的状态:

.state('app.searchResults', 
            {
                url: '/searchResults',
                views:
                {
                    'menuContent': { templateUrl: 'templates/searchResult.html', controller: 'stateResultController' }
                },
                params: 
                {
                    'searchQuery': ''
                }
            })

And finally, the controller associated with the app.searchResults state:

最后,与app.searchResults状态相关联的控制器:

.controller('stateResultController', function ($scope, $state, $stateParams, $http) {
        $scope.searchQueryInput = $stateParams.searchQuery;
    });

#10


3  

And in my case of a parent/child state. all the parameters declared in child state has to be known by the parent state

对于父/子状态。子状态中声明的所有参数必须由父状态知道

        .state('full', {
            url: '/full',
            templateUrl: 'js/content/templates/FullReadView.html',
            params: { opmlFeed:null, source:null },
            controller: 'FullReadCtrl'
        })
        .state('full.readFeed', {
            url: '/readFeed',
            views: {
                'full': {
                    templateUrl: 'js/content/templates/ReadFeedView.html',
                    params: { opmlFeed:null, source:null },
                    controller: 'ReadFeedCtrl'
                }
            }
        })

#11


2  

The solution we came to having a state that took 2 parameters was changing:

我们得到的结果是有两个参数的状态在改变:

.state('somestate', {
  url: '/somestate',
  views: {...}
}

to

.state('somestate', {
  url: '/somestate?id=:&sub=:',
  views: {...}
}

#12


0  

If this is a query parameter that you want to pass like this: /toState?referer=current_user

如果要传递的查询参数是:/toState?referer=current_user

then you need to describe your state like this:

然后你需要这样描述你的状态:

$stateProvider.state('toState', {
  url:'toState?referer',
  views:{'...'}
});

source: https://github.com/angular-ui/ui-router/wiki/URL-Routing#query-parameters

来源:https://github.com/angular-ui/ui-router/wiki/URL-Routing查询参数