在这种情况下,我建议选择view inheritance
(not controller
, not state
)。在这里查看更多详细信息:
- 如何在 angularjs ui-router 中的状态之间共享 $scope 数据? https://stackoverflow.com/q/27696612/1679310
- 如何继承ui-router中的解析数据 https://stackoverflow.com/q/26513746/1679310
有一个工作示例 http://plnkr.co/edit/iCcyvjZ26Et5UPmkttbR?p=preview
我们需要的是一个'root'
状态。这将是超级家长任何其他的state
(国家家属)。这可能是状态定义:
$stateProvider
.state('root', {
abstract: true,
templateUrl: 'layout.tpl.html',
controller: MyNamespace.RootCtrl,
})
.state('login', {
parent: "root",
url: "/login",
templateUrl: 'tpl.html',
controller: MyNamespace.LoginCtrl,
})
.state('home', {
parent: "root",
url: "/home",
templateUrl: 'tpl.html',
controller: MyNamespace.HomeCtrl,
})
甚至其他一些国家等级制度也会以此开始'root'
state:
$stateProvider
.state('parent', {
parent: "root",
url: "/parent",
templateUrl: 'tpl.html',
controller: MyNamespace.ParentCtrl
})
.state('parent.child1', {
url: "/child1",
templateUrl: 'tpl.html',
controller: MyNamespace.Child1Ctrl
})
.state('parent.child2', {
url: "/child2",
templateUrl: 'tpl.html',
controller: MyNamespace.Child2Ctrl
})
我们可以看到很多controllers:...
正在被定义,它们是:
module MyNamespace {
// the real SUPER parent of all states
// but it is about VIEW inheritance (its $scope)
// not about controller hierarchy
export class RootCtrl extends BaseController {
}
export class HomeCtrl extends BaseController {
}
export class LoginCtrl extends BaseController {
}
export class ParentCtrl extends BaseController {
}
export class Child1Ctrl extends BaseController {
}
export class Child2Ctrl extends BaseController {
}
}
正如片段注释中提到的 - 存在继承,但只是在代码级别。通过的$scope
由视图层次结构继承。
视图层次结构中的第一个控制器是RootCtrl
事实上,这将是唯一分配(创建)共享参考模型的人rootSetting : {}
它们都源自这个控制器基础:
module MyNamespace {
export interface IRootSetting {
hideNavbar: boolean;
}
export interface IMyRootScope extends ng.IScope {
rootSetting: IRootSetting
}
export interface IBaseScope extends IMyRootScope {
}
export class BaseController {
public hideNavbar: boolean;
static $inject = ['$scope', '$state'];
constructor(public $scope: IBaseScope,
protected $state: ng.ui.IStateService) {
// will be in fact assigned in the RootCtrl only
// all others (children) will get that reference
// via scope inheritance
$scope.rootSetting = $scope.rootSetting || {hideNavbar: false};
if ($state.current.url === '/login') {
this.$scope.rootSetting.hideNavbar = true;
} else {
this.$scope.rootSetting.hideNavbar = false;
}
}
}
}
有了这个根模板,就可以了:
<div>
<div ng-if="!rootSetting.hideNavbar">
... // navbar
</div>
<div ui-view="">
// standard content of child views
</div>
</div>
我们可以看到,这里我们评估共享参考模型rootSetting
及其财产hideNavbar
这才是真正的优势view inheritance
与UI-Router
.
检查实际情况here http://plnkr.co/edit/iCcyvjZ26Et5UPmkttbR?p=preview