角度更新和清除工厂变量

时间:2015-05-20 05:33:22

标签: angularjs angularjs-scope angular-routing angular-services

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

厂:

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>

1 个答案:

答案 0 :(得分:2)

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

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