1つのコントローラーで標準のrouteProviderセットアップを使用して、IDの有無にかかわらずURLを処理する1つの方法は次のとおりです。
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