【问题标题】:Angular updating and clearing factory variables角度更新和清除工厂变量
【发布时间】:2015-08-01 04:34:57
【问题描述】:

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

结果.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>

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 如果它解决了您的问题,您可以接受答案。
    • 美观、简洁、优雅、快速。
    猜你喜欢
    • 2018-11-13
    • 2015-03-12
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多