AngularJS:在 angular-ui-router 中使用 $state.go 将数据传递给状态 [英] AngularJS : Pass data to state with $state.go in angular-ui-router
问题描述
我正在制作一个文档编辑器.文档可以是Type A或Type B,通过url通过document id访问,但是id并没有说明文档是Type A还是B.
I'm making a document editor. Documents can be Type A or Type B. They are accessed by url by document id, but the id does not make it clear if the document is of type A or B.
因此,我需要通过 id 加载文档,根据其数据确定其类型,然后将其传递给 TypeAController 或 TypeBController.
So, I need to load the document by id, determine its type from its data, and then pass it to either the TypeAController or TypeBController.
现在,使用 ui-router,我有这样的事情:
Right now, with ui-router, I have something like this:
$stateProvider
.state('loading', {
url: '/{documentId}',
template: 'Loading...',
controller: function ($stateParams, $state) {
loadDocument($stateParams.documentId)
.then(function (loadedDocument) {
if (loadedDocument.type === 'A') {
$state.go('EditA');
} else if (loadedDocument.type === 'B') {
$state.go('EditB');
}
})
}
})
.state('A', {...})
.state('B', {...})
加载状态加载文档,确定其类型,然后进入下一个状态.
The loading state loads the document, determines its type, and then goes to the next state.
但令人沮丧的是,我找不到将加载的文档实际传递到下一个状态的方法!我可以创建一个全局服务,我可以在其中插入文档,或者我可以只传递文档的 id 并在每个状态下再次加载它(希望这次从缓存中),但是这些方法太笨重了,其他一切关于 angular 和 angular-ui 已经很流畅了.
Frustratingly, though, I can't find a way to actually pass the loaded document to the next states! I can make a globalish service into which I can insert the document, or I can just pass the id of the document along and load it again in each state (hopefully from a cache this time), but these methods are so clunky and everything else about angular and angular-ui has been so smooth.
有什么建议吗?
推荐答案
一种解决方案可能是将其移动到所有子级都可以使用的父状态.像这样:
One solution could be to move it to the parent state, which is available to all children. Something like this:
$stateProvider
.state('loading', {
url: '/{documentId}',
template: 'Loading...',
controller: function ($scope, $stateParams, $state) {
loadDocument($stateParams.documentId)
.then(function (loadedDocument) {
// assign the document to the parent model $scope
// in this case $scope.model.doc
$scope.model = { "doc" : loadedDocument };
if (loadedDocument.type === 'A') {
$state.go('.EditA');
} else if (loadedDocument.type === 'B') {
$state.go('.EditB');
}
})
}
})
.state('loading.EditA', {...}) // here we can use the $scope.model.doc
.state('loading.EditB', {...}) // in every child state
$scope.model.doc
表示对共享文档的引用.
The $scope.model.doc
represents the reference to the shared document.
这里(UI-路由器示例 - contact.js) 我们可以看到父级如何设置联系人集合,所有子状态都在访问它.示例
Here (UI-Router example - contact.js) we can see how parent is setting the contacts collection, all child states are accessing it. The example in action
这篇关于AngularJS:在 angular-ui-router 中使用 $state.go 将数据传递给状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!