【发布时间】:2018-05-13 10:11:21
【问题描述】:
我正在尝试在打开模式时动态更新视图上的 URL/状态,并在首次显示视图时处理自动打开模式。我正在使用 1.x 版本的 UI Router 和 AnguarJS 组件。我遇到的问题是当我更新状态时,$onInit() 被触发;换句话说,打开模态会导致打开第二个模态。
这是我处理更改状态的方式:
showModal() {
const modal = this.$uibModal.open({
component: 'viewModal',
size: 'lg'
})
const resetState = () => {
console.log('resetting state ...')
this.$state.go('.', {
id: this.$state.params.id
}, {
inherit: false,
notify: false,
reload: false,
location: 'replace'
})
}
modal.opened.then(() => {
console.log('opening ...')
this.$state.go('.', {
foo: 'bar'
}, {
notify: false,
reload: false,
location: 'replace'
})
})
// The 'catch' is due to the promise being rejected with 'backdrop click'
// when clicking on the background, though it doesn't always work, but
// that's another issue entirely
modal.closed.then(resetState).catch(resetState)
}
这是相关的$onInit() 代码
if (this.$state.params.foo) {
this.showModal()
}
这是路线的样子
export default function routing ($stateProvider) {
$stateProvider
.state({
name: 'exampleView',
url: '/example/{id}?foo',
component: 'exampleComponent'
})
}
我曾认为将reload 和notify 设置为false 会阻止重新加载视图,但事实并非如此。有没有更好的方法来更新状态而不触发$onInit?我应该直接使用window.location 吗?我希望用户能够在打开模式的情况下加载此视图。我不一定需要历史支持,所以我愿意在打开/关闭模式时删除更新 URL,但如果可能的话我更愿意保留它。
【问题讨论】:
-
在
$onInit()之前验证是否打开了模式以防止执行该操作 -
我想过,但是 AngularUI 的(Bootstrap)模态类没有那个功能,所以我需要进入 DOM 并查看 body 标签上的类。当然可行,但不是很干净。我尝试在控制器上设置一个属性,但这在状态更改之间不会持续存在。
-
重构代码以使模式从服务中运行。然后服务可以跟踪模态的打开/关闭状态。
标签: angularjs angular-ui-router angular-components