这是使用标准 routeProvider 设置和一个控制器处理带和不带 id 的 url 的一种方法:
JS:
var app = angular.module('plunker', []);
app.config(function($routeProvider){
return $routeProvider
.when('/', {
controller: 'HomeController',
templateUrl: 'home.html'
})
.when('/:id', {
controller: 'HomeController',
templateUrl: 'home.html'
})
.otherwise({ redirectTo: '/' });
});
app.controller('HomeController',
[
'$scope',
'$routeParams',
function($scope, $routeParams) {
if($routeParams.id){
$scope.id = $routeParams.id;
// handle scenario when there is an id in URL
return;
}
// handle scenario when there is no id
$scope.id = 'no ID!!';
}
]
);
Plunker
这是另一种方式,不使用 ng-view 并依赖 $location 服务:
var app = angular.module('plunker', []);
app.config(
['$locationProvider',
function($locationProvider) {
$locationProvider.html5Mode(true);
}
]
);
app.controller('HomeController',
[
'$scope',
'$location',
function($scope, $location) {
$scope.$watch(function(){
return $location.hash();
},
function(id){
$scope.id = id;
}
);
$scope.$watch('id', function(id){
if(id){
// handle scenario when there's id available
return;
}
// handle scenario when there is no id
});
}
]
);
Plunker