Can angularjs routes have default parameter values?

后端 未结 5 1790
余生分开走
余生分开走 2020-12-05 17:21

Can I set a default value of a parameter of a route in AngularJS? Is there a way to have /products/123 and /products/ handled by the same route ?

5条回答
  •  盖世英雄少女心
    2020-12-05 18:02

    I had a similar requirement. What i did was to create a function to resolve. Something like below

    myModule.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
     when('/products/', resolveProduct()).            
     when('/products/:productId', resolveProduct())
    }]);
    
    
    function ProductsCtrl($scope, $routeParams) {
    $scope.productId = $routeParams.productId;
    }
    
    function resolveProduct() {
       var routeConfig = {
          templateUrl: 'products.html', 
          controller: ProductsCtrl,
          resolve: {
             productId: ['$route', function($route){
                var params = $route.current.params;
                params.productId =  params.productId || 123;
             }]
          }
       }
    
       return routeConfig;
    }
    

提交回复
热议问题