AngularJS : Pass data to state with $state.go in angular-ui-router

前端 未结 2 1074
臣服心动
臣服心动 2020-12-16 02:26

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

相关标签:
2条回答
  • 2020-12-16 03:13

    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
    

    The $scope.model.doc represents the reference to the shared document.

    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

    0 讨论(0)
  • 2020-12-16 03:21

    You could have a Documents service which owns and provides an API to all the document data. The controllers then inject the Documents service, and reference the document they're interested in on their scope.

    Something like:

    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;
      });
    
      ...
    
    })
    
    0 讨论(0)
提交回复
热议问题