Preserve state with Angular UI-Router

后端 未结 3 1470
我寻月下人不归
我寻月下人不归 2021-01-31 10:29

I have an app with a ng-view that sends emails to contact selected from a contact list. When the users select \"Recipient\" it shows another view/page where he can search, filte

相关标签:
3条回答
  • 2021-01-31 11:08

    The solution i have gone with is using services as my data/model storage. they persist across controller changes.

    example

    the user service ( our model that persists across controller changes )

    app.factory('userModel', [function () {
        return {
            model: {
                name: '',
                email: ''
            }
        };
    }]);
    

    using it in a controller

    function userCtrl($scope, userModel) {
        $scope.user = userModel;
    }
    

    the other advantage of this is that you can reuse your model in other controllers just as easly.

    0 讨论(0)
  • 2021-01-31 11:10

    I'm not sure if this is recommended or not, but I created a StateService to save/load properties from my controllers' scopes. It looks like this:

    (function(){
        'use strict';
    
        angular.module('app').service('StateService', function(){
    
            var _states = {};
    
            var _save = function(name, scope, fields){
                if(!_states[name])
                    _states[name] = {};
                for(var i=0; i<fields.length; i++){
                    _states[name][fields[i]] = scope[fields[i]];
                }
            }
            var _load = function(name, scope, fields){
                if(!_states[name])
                    return scope;
                for(var i=0; i<fields.length; i++){
                    if(typeof _states[name][fields[i]] !== 'undefined')
                        scope[fields[i]] = _states[name][fields[i]];
                }
                return scope;
            }
    
            // ===== Return exposed functions ===== //
            return({
                save: _save,
                load: _load
            });
    
        });
    })();
    

    To use it, I put some code at the end of my controller like this:

    angular.module('app').controller('ExampleCtrl', ['$scope', 'StateService', function ($scope, StateService) {
        $scope.keyword = '';
        $scope.people = [];
    
        ...
    
        var saveStateFields = ['keyword','people'];
        $scope = StateService.load('ExampleCtrl', $scope, saveStateFields);
        $scope.$on('$destroy', function() {
            StateService.save('ExampleCtrl', $scope, saveStateFields);
        });
    }]);
    
    0 讨论(0)
  • 2021-01-31 11:15

    I have found Angular-Multi-View to be a godsend for this scenario. It lets you preserve state in one view while other views are handling the route. It also lets multiple views handle the same route.

    You can do this with UI-Router but you'll need to nest the views which IMHO can get ugly.

    0 讨论(0)
提交回复
热议问题