angularjs 路由可以有默认参数值吗? [英] Can angularjs routes have default parameter values?

查看:27
本文介绍了angularjs 路由可以有默认参数值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 AngularJS 中设置路由参数的默认值吗?有没有办法让 /products/123/products/ 通过相同的路线处理?

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 ?

我希望重构我现有的代码,如下所示:

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

路由不允许正则表达式匹配参数

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 路由没有名称.
  • 您不会从定义的路由中构建 URL.
  • 您在路由定义中没有逻辑(也就是函数).

更简单的路线 = 更多定义它们的线 = 更少的麻烦.

Simpler routes = more lines to define them = less headaches working with them.

注意:请记住这个问题,这个答案是针对新路由/资源实现之前的旧版本 AngularJS(我认为是 1.0).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆