Angular 更新和清除工厂变量

Angular updating and clearing factory variables

我正在创建一个单页应用程序,用户在其中搜索术语,结果保存在一个变量中,然后路由一个显示结果的新页面。我有这个功能,但是我希望当用户 returns 到上一页时清除变量,最重要的是当用户注销时。这样做的正确方法是什么?我希望工厂为我想要的某些页面保存内容,并为我不想要的某些页面清除它们,例如 "home" 或 "logout".

工厂:

angular.module('firstApp')
    .factory('fact', function () {
    var service = {};
    var _information = 'Default Info';

    service.setInformation = function(info){
      _information = info;
    }

    service.getInformation = function(){
      return _information;
    }
    return service;
});

控制器:

angular.module('firstApp')
    .controller('InformationCtrl', function($scope, $http, $location, fact) {
        $scope.message = 'Hello';
        $scope.result = fact.getInformation();
        $scope.sub = function(form) {
            console.log($scope.name);
            $scope.submitted = true;
            $http.get('/wiki', {
                params: {
                    name: $scope.name,
                }
            }).success(function(result) {
                console.log("success!");
                $scope.result = result;
                    fact.setInformation(result);
                $location.path('/informationdisplay');
            });;
        }
    });

路线

angular.module('firstApp')
  .config(function ($routeProvider) {
    $routeProvider
      .when('/information', {
        templateUrl: 'app/information/input.html',
        controller: 'InformationCtrl',
        authenticate : true
      })
        .when('/informationdisplay', {
        templateUrl: 'app/information/results.html',
        controller: 'InformationCtrl',
        authenticate : true
      });
  });

input.html

<div class="row">
    <div class="col-md-6 col-md-offset-3 text-center">
         <p>{{result}}</p>
         <form class="form" name="form" ng-submit="sub(form)" novalidate>
            <input type="text" name="name" placeholder="Name" class="form-control" ng-model="name">
            </br>
            <button class="btn btn-success" type="submit" class="btn btn-info">Check</button>
    </div>
</div>

results.html

<div ng-include="'components/navbar/navbar.html'"></div>
<div class="row">
    <div class="col-sm-4 col-sm-offset-4">
            <h2>Information Results</h2>
            <p>{{result}}</p>   
    </div>
  </div>
</div>

如果您希望它在更改路由时擦除该值(我认为注销也应该更改路由),您可以观看 $routeChangeStart 事件并让它在它发生时擦除该值。您将该函数放在 module.run 块中:

app.run(function ($rootScope, fact) { 
    $rootScope.$on("$routeChangeStart",function(event, next, current){
        fact.setInformation(null);
    });
});