所以我 Angular 这条路线
问题是:volume 并不总是可以从我正在使用的 api 中获得 有时音量有有时没有 那么我是否可以将 :volume parm 设为可选,以便仅在存在时显示它,而在未给出时将删除它
书籍有卷时的 url 为 book/read/:name/:volume/:chapter/:id
当它没有卷时,它是book/read/:name/:chapter/:id
'use strict';
angular.module('myApp.read', [])
.config( function($stateProvider) {
$stateProvider.state('read', {
url: '/read/:name/:volume?/:chapter/:id',
templateUrl: 'pages/read/read.html',
controller: 'ReadController',
onEnter: function($rootScope){
$rootScope.bodyClass = 'read';
}
});
})
.controller('ReadController', function($scope, $http, $stateParams, $state) {
var name = $stateParams.name; //getting name
var volume = $stateParams.volume; //getting volume
var chapter = $stateParams.chapter; //getting chapter
var id = $stateParams.id; //getting id
$scope.state = $state.current;
$scope.params = $stateParams;
if (volume && volume.length) volume += '/';
$http.get('http://localhost:1337/book/read/' + name + '/' + volume + chapter + '/' + id).success(function(response) {
$scope.read = response;
});
});
最佳答案
我不确定一组中间的一个,但要使参数可选,您要做的就是在它后面加上 ?
所以您的将是: url: '/read/:名称/:卷?/:章节/:id'
当然,您必须更新 Controller 才能处理它不存在的情况。例如:
.controller('ReadController', function($scope, $http, $stateParams, $state) {
var name = $stateParams.name; //getting name
var volume = $stateParams.volume; //getting volume
var chapter = $stateParams.chapter; //getting chapter
var id = $stateParams.id; //getting id
$scope.state = $state.current;
$scope.params = $stateParams;
if (volume && volume.length) volume += '/';
$http.get('http://localhost:1337/book/read/' + name + '/' + volume + chapter + '/' + id).success(function(response) {
$scope.read = response;
});
});
关于javascript - 如何使routeParams可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31731693/