0

次の問題があります:

AngularJS アプリでは$routeProvider、さまざまな部分をアプリケーションにロードするために使用します

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'});
}]);

私の UserCtrl には、操作できるユーザーのリストが表示されます。次のようなjsonからユーザーのリストを読み取ります。

{"users":[{"id":1,"name":"test user 2","mail":"test@gmail.com","ringer":true,"active":true},{"id":2,"name":"test user 1","mail":"test@page.com","ringer":false,"active":true},{"id":3,"name":"admin","mail":"admin@example.com","ringer":false,"active":true}]}

私はusers.htmlデータをロードするためにサービスを呼び出すコントローラーを持っています

    '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;    
  }])
;

そして最後にサービス:

    '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 };

});

私が抱えている問題は次のとおりです。ロードするたびusers.htmlに、データがjsonファイルからリロードされます。データを一度だけロードして、コントローラーに保持したい。ここで、データに変更を加え、別のビューに切り替えて戻ってくると、すべての変更が失われます。

どんな助けでも大歓迎です。

ありがとう、ズビネック

4

1 に答える 1