您可以使用 angular-ui 团队 ui-router ( https://github.com/angular-ui/ui-router ) 来跟踪有效的一组可选参数。为此,您的代码将类似于:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.0.x" src="http://code.angularjs.org/1.0.7/angular.min.js" data-semver="1.0.7"></script>
<script src="angular-ui-states.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li><a href="" ng-click="transition('foo', {var1: 'hello', var2: 'world'})">Go to Foo</a></li>
<li><a ng-href="#/bar?var1={{bazVars.var1}}&var2={{bazVars.var2}}">Go to Bar</a></li>
<li><a href="" ng-click="transitionLocation('baz', {var1: 'sionara', var2: 'world', var3: 'meh'})">Go to Baz</a></li>
<li><a href="#/bah">Go to Bah</a></li>
</ul>
<div ui-view></div>
<pre>
{{$stateParams}}
</pre>
</body>
</html>
使用 stateprovider 设置来接受这些可选参数:
var app = angular.module('plunker', ['ui.state'])
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('foo',
{
url: '/foo?var1&var2',
template: '<h1>Foo</h1>',
controller: 'subCtrl'
})
.state('bar',
{
url: '/bar?var1&var2',
template: '<h1>Bar</h1>',
controller: 'subCtrl'
})
.state('baz',
{
url: '/baz?var1&var2&var3',
template: '<h1>Baz</h1>',
controller: 'subCtrl'
})
.state('bah',
{
url: '/bah?var1&var2&var3',
template: '<h1>Bah</h1>',
controller: 'subCtrl'
});
}])
.run(['$stateParams', '$rootScope', function($stateParams, $rootScope){
$rootScope.$stateParams = $stateParams
}]);
app.controller('MainCtrl', function($scope, $state, $location) {
$scope.bazVars = {
var1: 'goodbye',
var2: 'world'
}
$scope.transition = function(name, options){
$state.transitionTo(name, options);
}
$scope.transitionLocation = function(name, options){
$location.path('/' + name);
for(key in options){
$location.search(key, options[key]);
}
console.log($location.url());
}
});
app.controller('subCtrl', function($scope, $stateParams){
console.log($stateParams);
})
上述工作 plunker:http ://plnkr.co/edit/ZVLApU92MVdIhlovailY?p=preview
请注意,ui-router 也允许使用点表示法进行嵌套状态,因此您可以使用相同的机制跟踪页面的子参数(请参阅https://github.com/angular-ui/ui-router/wiki/嵌套状态-%26-嵌套视图)。