Ril*_*ark 10 angularjs angular-ui-router
我正在制作文档编辑器.文档可以是类型A或类型B.它们可以通过文档ID通过URL访问,但是如果文档是类型A或B,则id不会清楚.
因此,我需要通过id加载文档,从其数据中确定其类型,然后将其传递给TypeAController或TypeBController.
现在,使用ui-router,我有类似的东西:
$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', {...})
Run Code Online (Sandbox Code Playgroud)
加载状态加载文档,确定其类型,然后进入下一个状态.
然而,令人沮丧的是,我无法找到将加载的文档实际传递到下一个状态的方法!我可以创建一个全局服务,我可以插入文档,或者我只需传递文档的id并在每个状态下再次加载它(希望这次从缓存中),但这些方法是如此笨重而且其他一切关于角度和角度ui一直很光滑.
有什么建议?
Rad*_*ler 11
一种解决方案可能是将其移至父状态,这对所有儿童都可用.像这样的东西:
$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
Run Code Online (Sandbox Code Playgroud)
的$scope.model.doc表示参照共享文档.
在这里(UI-Router示例 - contact.js)我们可以看到父如何设置联系人集合,所有子状态都在访问它.行动中的例子
您可以拥有一个Documents拥有并为所有文档数据提供API 的服务.然后,控制器注入Documents服务,并引用他们对其范围感兴趣的文档.
就像是:
app.service('Documents', function(){
Documents = {};
return {
open: function(doc_id) { ... } // loads and caches doc (if not already cached) and returns a promise with a reference to Documents[doc_id]
sync: function(doc_id) { ... } // sync doc with server
close: function(doc_id) { ... } // remove doc_id from Documents
};
});
app.controller('editX', function($scope, $stateParams, Documents){
Documents.open($stateParams.documentId).then(function(ref){
$scope.document = ref;
});
...
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31805 次 |
| 最近记录: |