Can angularjs routes have optional parameter values?

前端 未结 4 998
清酒与你
清酒与你 2020-11-28 05:37

Can I set a route with optional params (same template and controller, but some params should be ignored if they don\'t exist?

So instead of writing the following two

相关标签:
4条回答
  • 2020-11-28 06:00

    Actually I think OZ_ may be somewhat correct.

    If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

    0 讨论(0)
  • 2020-11-28 06:08

    It looks like Angular has support for this now.

    From the latest (v1.2.0) docs for $routeProvider.when(path, route):

    path can contain optional named groups with a question mark (:name?)

    0 讨论(0)
  • 2020-11-28 06:22

    Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

    You can use a function to generate the template string:

    var app = angular.module('app',[]);
    
    app.config(
        function($routeProvider) {
            $routeProvider.
                when('/', {templateUrl:'/home'}).
                when('/users/:user_id', 
                    {   
                        controller:UserView, 
                        templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                    }
                ).
                otherwise({redirectTo:'/'});
        }
    );
    
    0 讨论(0)
  • 2020-11-28 06:25

    Like @g-eorge mention, you can make it like this:

    module.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
    }]);
    

    You can also make as much as u need optional parameters.

    0 讨论(0)
提交回复
热议问题