有一个plunker http://plnkr.co/edit/YkfRUOMlgS5qW9f4ET6p?p=preview,这应该有助于给出答案:
我应该使用 UI Router 吗?列表和详细信息页面是两个不同的屏幕。
如果我们继续productDetails
状态,我们确实失去了一些东西(如果不是很多的话).
In the example http://plnkr.co/edit/YkfRUOMlgS5qW9f4ET6p?p=preview我们可以看到这个状态定义:
$stateProvider
// parent state for products.detail
// the important thing here is that it must contain
// ui-view="details", because the child is targeting it
.state('products', {
url: '/products',
templateUrl: 'products.list.html',
controller: 'productListCtrl'
})
// here, we will hook into the parent ui-view
// that means one essential thing:
// our scope, will be inherited from parent
.state('products.detail', {
url: '^/:id',
views: {
'detail': {
templateUrl: 'products.detail.html',
controller: 'productDetailCtrl'
}
},
})
到目前为止,我们已经看到了标准嵌套状态父/子。接下来我们将定义子状态,同时针对根ui-view=""
// this one is as the productDetails
// it skips parent and targets the root view
// despite of the fact, that it is defined as sub-state of the products !
// we won't get anything from parent state
.state('products.detailAsRoot', {
url: '^/product/:id',
views: {
'@': {
templateUrl: 'products.detail.html',
controller: 'productAsRootCtrl'
}
},
});
首先,这里对 javascript/scopes 中的继承进行了详尽的解释:
- AngularJS 中的范围原型/原型继承有哪些细微差别? https://stackoverflow.com/questions/14049480/
而且,重要的是,ui-router 中的范围是以“视图嵌套”的方式继承的
基本引用:
请记住范围属性如果状态视图是嵌套的,则仅沿状态链继承。范围属性的继承与状态的嵌套无关,而与视图(模板)的嵌套有关。
那么这个答案是关于什么呢?说:如果我们会使用ui-router
,最大的好处就是作用域继承。父母可以做某件事一次......孩子可以重复使用它。
另请参阅:
- 当状态更改时,如何防止命名视图重新加载? AngularJS UI 路由器 https://stackoverflow.com/questions/23568908/
- Angular UI Router 嵌套状态在子状态中解析 https://stackoverflow.com/a/20558850/1679310
- The plunker http://plnkr.co/edit/YkfRUOMlgS5qW9f4ET6p?p=preview与此处描述的工作示例