angularjs路线可以有默认参数值? [英] Can angularjs routes have default parameter values?
问题描述
我可以设置angularjs路线的参数的默认值?有没有办法让'/产品/ 123'和'/产品/'通过相同的途径来处理?
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 ?
我期待我的重构现有code,它看起来像:
I'm looking to refactor my existing code, which looks like:
myModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/products/', {templateUrl: 'products.html', controller: ProductsCtrl}).
when('/products/:productId', {templateUrl: 'products.html', controller: ProductsCtrl})
}]);
function ProductsCtrl($scope, $routeParams) {
$scope.productId = typeof($routeParams.productId) == "undefined" ? 123 : $routeParams.productId;
}
它的工作原理,但它不是很优雅。有没有更好的办法?
It works, but it's not very elegant. Is there a better way ?
推荐答案
AngularJS
不允许默认值路由参数。
AngularJS
does not allow default values for route parameters.
但路线(以 AngularJS
)的不应该有默认参数。
资源可以有默认参数。
在 AngularJS
如果您希望使用一个可选的参数的路线,这实际上是两个不同的路线。
In AngularJS
if you want a route with an optional parameter, these are actually two different routes.
为什么?
-
路线应该是简单
Routes should be simple
路线不允许正规的前pressions的参数匹配
Routes does not allow regular expressions matching for parameters
路线是不是它公开的API在应用程序中工作(不同于资源做)。路线只是其中的配置使用模板和控制器连接的URL。因此,有更多的途径是更好的:
Routes are not something which exposes an API to work in your application (unlike Resources do). Routes are just configuration which connects a URL with a template and a controller. Thus having more routes is better:
-
有清楚哪些路由映射的URL。
It is clear which route maps to which url.
这是更冗长,但更简单易读。有更复杂的路线将创建一个陡峭的学习曲线,其中AngularJS并不需要一个。
It is more verbose, but simpler to read. Having more complex routes would create a steeper learning curve where AngularJS does not need one.
不像有路由服务器端框架
Unlike server-side frameworks which have routes
- AngularJS路线没有名字。
- 您没有从定义的路由建立的网址。
- 您没有在路由定义逻辑(a.k.a函数)。
简单路线=更多的线来定义它们=不头痛与他们合作。
Simpler routes = more lines to define them = less headaches working with them.
注意:请记住这个问题,这个答案是旧版本AngularJS(1.0我认为)pre-约会新航线/资源实施
NOTE: Please keep in mind the question and this answer are for an old version of AngularJS (1.0 I think) pre-dating the new routes/resources implementation.
这篇关于angularjs路线可以有默认参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!