2

我已经为我的商店应用程序定义了状态,但我不确定我是否正确地执行了此操作。由于我在url中有多个可选参数,所以我不知道该如何实现它。Angular ui路由器可选url params

.state('app.products', { 
    abstract: true, 
    views: { 
     '[email protected]': { 
      templateUrl: 'app/products/views/product.html' 
     }, 
     '[email protected]': { 
      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可以womanfootwear可以cloth(其中最后PARAM将如shirts)和所有上述可能的组合。

我不确定是否必须单独制作每个状态,或者我可以用除此之外的其他状态来处理所有这些情况?

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

我只是找不到任何类似的在线,所以如果有人有任何链接,也将是有益的。

回答

1

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

下面是一个例子,让你开始:

.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这个/app/products/:gender/:category/:type

做这种方式是,在父状态定义意见会自动包含在所有子的第二个好处指出,除非你明确地将其覆盖:

.state('app.products.gender.category', { 
    url: '/:category', 
    views: { 
    '[email protected]': {templateUrl: 'foo.html'}, 
    '[email protected]': {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 
    '[email protected]': {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 docs以获取帮助您减少编码的配置。
+0

谢谢,很好的建议,虽然我想避免这么多州,现在看起来好多了。我将app.products状态添加为抽象和定义的url:'{{page,brands}',因为所有孩子(您在上面写的)都会有这些可选参数。这是在抽象状态上定义可选查询参数的正确方法吗?当然我加了params:{page:{value:'1',squash:true},品牌:{value:null,squash:true}}。 – zhuber