Glo*_*opy 9 javascript routes angularjs
我有一个类似的路由,应根据参数是否为数字加载不同的视图和控制器.例:
/artists/2
应该ArtistsIndexController
有一个观点/www/artists/index.html
/artists/name
应该ArtistsProfileController
有一个观点/www/artists/profile.html
理想情况下,我会使用类似的东西:
$routeProvider.when("/artists/:page", {
templateUrl: "/www/artists/index.html",
controller: "ArtistsIndexController"
});
$routeProvider.when("/artists/:name", {
templateUrl: "/www/artists/profile.html",
controller: "ArtistsProfileController"
});
Run Code Online (Sandbox Code Playgroud)
数字在哪里:page
而:name
不是.
另一种方法是使用ui-router,它支持路由的正则表达式(在一系列其他东西中),这将允许:
$stateProvider.state("artists-index", {
url: "/artists/{page:[0-9]*}",
templateUrl: "/www/artists/index.html",
controller: "ArtistsIndexController"
});
$stateProvider.state("artists-profile", {
url: "/artists/{name}",
templateUrl: "/www/artists/profile.html",
controller: "ArtistsProfileController"
});
Run Code Online (Sandbox Code Playgroud)
我现在使用这个作为解决方案,并且对替代方案感兴趣!
1) 创建一个将在控制器中加载并动态查看的通用模板:
<div ng-controller="controller" ng-include src="templateUrl"></div>
Run Code Online (Sandbox Code Playgroud)
在此示例中,我将此视图放置在/www/shared/dynamic-controller.html
2) 创建一个控制器来检查路由参数以确定要加载的控制器和视图:
angular.module('appName').
controller('ArtistsDynamicRouteController', ['$scope', '$controller', '$routeParams', function($scope, $controller, $routeParams) {
if(/^\d+$/.test($routeParams.pageOrId)) {
// when pageOrId is a page (number) we want to load the ArtistsIndexController
$scope.controller = $controller('ArtistsIndexController', { $scope: $scope }).constructor;
$scope.templateUrl = '/www/artists/index.html';
} else {
// when pageOrId is an id (non-number) we want to load the ArtistsProfileController
$scope.controller = $controller('ArtistsProfileController', { $scope: $scope }).constructor;
$scope.templateUrl = '/www/artists/profile.html';
}
}]);
Run Code Online (Sandbox Code Playgroud)
3) 无论参数类型如何,都使用一个路由:
// handles both /artists/2 and /artists/username
$routeProvider.when("/artists/:pageOrName", {
templateUrl: "/www/shared/dynamic-controller.html",
controller: "ArtistsDynamicRouteController"
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14549 次 |
最近记录: |