AngularJS – State Service

‘use strict’;

/**
* @ngdoc service
* @name interceptcms.stateService
* @description
* # stateService
* Factory in the interceptcms.
*/

function stateHistory($state) {

var history = [];
var idx = 0;

// function loadPrevious(idx) {
//   $state.go(history[idx].state, history[idx].params);     
// }

function addState() {
  history.push({state: $state.current, params: $state.params});
  idx += 1;
}

return {

    loadListView: function(model) {
        for (var i = history.length - 1; i >= 0; i--) {
          if (history[i].params.id === undefined && history[i].params.model === model) {
            $state.go(history[i].state, history[i].params); 
          }
        }   
    },

    loadRecordView: function(model, id) {
        var params = {};
        params.id = id.replace('/', '');
        params.model = model;
        $state.go("/:model/:id", params); 
        //$state.transitionTo("/:model/:id", params, { reload: true, inherit: true, notify: true });
    },

      // FORM SUBMISSION CREATES AN ADDITIONAL STATE
    goBack: function (model, createEdit, id) {
        //loadListView($state.params.model);      
        if (id) {
          this.loadRecordView(model, id);
        } 
    },

    stateLoaded: function () {
        addState();
    },

    listView: function(model, id) {
        if (!id) {
          this.loadListView(model);
        } else {
          this.loadRecordView(model, id);
        }
    }

};

}

angular.module(‘interceptcms’)
.factory(‘stateService’, stateHistory);

Leave a Reply

Your email address will not be published. Required fields are marked *