keep data in controller while routing in angular

1k views Asked by At

I have following problem:

In AngularJS app I use $routeProvider to load different parts into application

config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'});
  $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'UserCtrl'});
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

In my UserCtrl I display list of users, which I can manipulate. I read the list of users from json, which looks like this:

{"users":[{"id":1,"name":"test user 2","mail":"[email protected]","ringer":true,"active":true},{"id":2,"name":"test user 1","mail":"[email protected]","ringer":false,"active":true},{"id":3,"name":"admin","mail":"[email protected]","ringer":false,"active":true}]}

In users.html I have controller, which calls service to load the data

    'use strict';

/* Controllers */

angular.module('myApp.controllers', []).
  controller('MyCtrl1', [function() {

  }])
  .controller('MyCtrl2', [function() {

  }])
  .controller('UserCtrl', ['$scope', 'UsersService', function($scope, UsersService) {
    //alert(UsersService.fetchData().length);
    UsersService.fetchData().then( function( data ){
      // Do whatever you want with data, like:
      $scope.users = data.users;
    });

    this.users = $scope.users;
    this.selected = [];
    this.searchTerm = '';

    $scope.selected = this.selected;    
  }])
;

And finally the service:

    'use strict';

/* Services */


// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).
  value('version', '0.1')
  .factory('UsersService', function($http, $q) {

  var data = [];

  function fetchData() {
    var deffered = $q.defer();
    if ( _isDataPresent() ) {
      deffered.resolve( _returnData() );
    } else {
      //var deffered = $q.defer();
      $http.get('php/users.php')
      .success(function (d) {
        deffered.resolve(d);
        data = d.users;
      });
      return deffered.promise;
    }
  }

  function _isDataPresent() {
    return data.length;
  }

  function _returnData() {
    return data;
  }

  return { fetchData : fetchData };

});

The problem which I have is following: Every time I load users.html, the data are reloaded from json file. I want to load data only once and keep them in my controller. Now, when I make some changes to the data, switch to different view and come back, all changes are lost.

Any help would be appreciated.

Thanks, Zbynek

1

There are 1 answers

8
avcajaraville On BEST ANSWER

This is a simple example of what I meant:

.factory( 'UsersService', function( $http, $q ) {

  var users = [];

  function fetchUsers() {
    var deffered = $q.defer();
    if ( _areUsersPresent() ) {
      deffered.resolve( _getUsers() );
    } else {
      $http.get('php/users.php')
      .success(function (response) {
        deffered.resolve(response.users);
        data = d.users;
      });
      return deffered.promise;
    }
  }

  function _areUsersPresent() {
    return ( users.length() ) ? true : false;
  }

  function _getUsers() {
    return users;
  }

  function setUsers( newUsers ) {
    users = newUsers;
  }

  return { fetchUsers : fetchUsers, setUsers : setUsers };

});

You can use this on your controllers as

UsersService.fetchUsers().then( function( users ){
  // Do whatever you want with data, like:
  $scope.users = users;
});

And, whenever you update the users on your controllers, you have to update the content of the service:

// Doing operations with $scope.service, when finish with them:
UsersService.setUsers( $scope.users );