gpt4 book ai didi

angularjs - 为多个状态设置默认 View AngularJS ui.router

转载 作者:行者123 更新时间:2023-12-03 00:02:50 25 4
gpt4 key购买 nike

我在 Angular 应用程序中有多个 View 。目前,我正在使用 ui.router 的 $stateProvider 来建立 View 。然而,我发现这非常乏味,因为我必须在每个州重复每个 View 。有没有办法为所有状态设置默认 View ,而不是在每个状态中重复它们?

$stateProvider
.state('default', {
url: '/default',
views:{
view_1: {
templateUrl: 'view1',
controller: function($scope){}
},
view_2: {
templateUrl: 'view2',
controller: function($scope){}
},
view_3: {
templateUrl: 'view3',
controller: function($scope){}
}
}
})
.state('changed_state', {
url: '/changed_state',
views:{
view_1: {
templateUrl: 'view1',
controller: function($scope){}
},
view_2: {
templateUrl: 'changed_view2',
controller: function($scope){}
},
view_3: {
templateUrl: 'view3',
controller: function($scope){}
}
}
})

我只想列出所有状态的默认 View 一次,然后只更改随每个状态更改而更改的 View 。即:

.state('default', {
url: '/default',
views:{
view_1: {
templateUrl: 'view1',
controller: function($scope){}
},
view_2: {
templateUrl: 'view2',
controller: function($scope){}
},
view_3: {
templateUrl: 'view3',
controller: function($scope){}
}
}
})
.state('changed_state', {
url: '/changed_state',
views:{
view_2: {
templateUrl: 'changed_view2',
controller: function($scope){}
}
}
})

谢谢

最佳答案

UI-Router 架构中已经存在这一点:

Nested States & Nested Views

我们将声明一个 super 基本状态(例如 'root' )。它甚至可以是抽象的以避免其初始化——但不是必须的。并且这个状态将定义所有默认 View 。任何子状态或孙子状态都可以替换以下任何默认值:

root状态

 .state('root', {
// url: '/default', - no url needed at all, but could be
abstract: true
views:{
'' : { templateUrl: 'layout.html'},

'view_1@root': {
templateUrl: 'view1',
controller: function($scope){}
},
'view_2@root': {
templateUrl: 'view2',
controller: function($scope){}
},
'view_3@root': {
templateUrl: 'view3',
controller: function($scope){}
}
});

上面我们可以看到,根状态注入(inject)了index.thml <div ui-view=""></div>它自己的模板 - 布局模板:

'' : { templateUrl: 'layout.html'},

因此,layout.html 中的所有命名 View 现在都可以填充默认 View ,我们只需使用绝对命名(请参阅下文)

'view_1@root': { // this will inject into the layout.html of current root state

一些更有趣的点。我们不使用 url...所以所有子状态都可以定义自己的。我们使用抽象...但这不是必须的。

子状态 - 这是从父状态获利的方式

.state('changed_state', {
parent: 'root' // this way we profit from parent
url: '/changed_state',
views:{
view_2: {
templateUrl: 'changed_view2',
controller: function($scope){}
},
// HERE all other views are unchanged

另请检查:

Multiple Named Views

View Names - Relative vs. Absolute Names

了解更多命名'view_1@root' (小引用)

Behind the scenes, every view gets assigned an absolute name that follows a scheme of viewname@statename, where viewname is the name used in the view directive and state name is the state's absolute name, e.g. contact.item. You can also choose to write your view names in the absolute syntax.

关于angularjs - 为多个状态设置默认 View AngularJS ui.router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27734497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com