繁体   English   中英

Angular ui 路由器可选的 url 参数

[英]Angular ui router optional url params

我已经为我的商店应用程序定义了状态,但我不确定我做得对。 由于我在 url 中有多个可选参数,我不确定我应该如何实现它。

.state('app.products', {
    abstract: true,
    views: {
        'content@': {
             templateUrl: 'app/products/views/product.html'
         },
         'productHeader@app.products': {
             templateUrl: 'app/products/views/product-header.html'
          }
    }
})

以上是我对产品页面的抽象视图。 产品将分为男士/女士以及子类别,例如:

www.example.com/man/

www.example.com/man/footwear/

www.example.com/man/footwear/shoes

Manfootwearshoes都是可选的,因为man PARAM可以是womanfootwearcloth (其中最后PARAM将如shirts )和上面的所有可能的组合。

我不确定是否必须分别设置每个状态,还是可以用除此状态之外的另一种状态来处理所有这些?

请注意, product header在这里不相关,如果需要良好的结构来删除它,我当然可以做到。

我只是在网上找不到任何类似的东西,所以如果有人有任何链接也会有帮助。

我最近做了一些非常相似的事情,将每个子类别 state 嵌套到其父类别 state 中 这样做的一些好处是,您不必在父状态中已定义的子状态中重复大量代码,也不必重新加载已在父状态中加载的数据和视图.

这是一个让您入门的示例:

.state('app.products', {
  abstract: true,
  url: '/products',
  views: {...}
})
.state('app.products.gender', {
  url: '/:gender',
  views: {...}
})
.state('app.products.gender.category', {
  url: '/:category',
  views: {...}
})
.state('app.products.gender.category.type', {
  url: '/:type',
  views: {...}
})

首先, url 会自动在子状态中堆叠 这意味着你只需要为每个子状态定义一个 url 参数,你仍然会得到这样的 url /app/products/:gender/:category/:type

这样做的第二个好处是,在父状态中定义的视图会自动包含在其所有子状态中,除非您明确覆盖它:

.state('app.products.gender.category', {
  url: '/:category',
  views: {
    'foo@someParentState': {templateUrl: 'foo.html'},
    'bar@someParentState': {templateUrl: 'bar.html'}
  }
})
.state('app.products.gender.category.type', {
  url: '/:type',
  views: {
    // foo.html is still rendered here
    // bar.html is replaced by baz.html
    'bar@someParentState': {templateUrl: 'baz.html'}
  }
})

从这个例子中看到的另一个好处是,当状态更改为app.products.gender.category.type时, foo.html 不会重新加载 例如,假设 foo.html 有一个很长的滚动列表,包含该类别中的类型。 如果用户点击列表中的某个项目将状态从app.products.gender.category更改为子状态app.products.gender.category.type ,则不会重新加载 foo 的长滚动列表,用户可以仍然可以看到他们点击的项目。 另一方面,如果该点击已将状态更改为非子状态,则列表可能已被重新加载(数据和所有),并且用户可能必须滚动才能看到他们点击的项目。

一些建议

  • 保持嵌套的状态名称简短。
  • 仅在绝对必要时才在层次结构中包含一个状态(我正在查看您的 app.products!)。
  • 这种技术有很多可能出错的方式,因此请务必查看ui-router 文档以了解可帮助您减少编码的配置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM