chgbj 2023-10-10 05:13 采纳率: 6.3%
浏览 15
已结题

Angular js的过滤器保留过滤条件

在使用Angular js的过滤器的时候,如果在当前页面输入过滤条件,进入新页面再返回当前页面的时候,怎么能保留刚刚的过滤条件?

  • 写回答

18条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2023-10-10 07:33
    关注
    获得0.30元问题酬金

    引自强大而免费的微信小程序:皆我百晓生。如有帮助,还望采纳。


    要保留过滤条件,你可以将过滤条件存储在 AngularJS 中的服务或者根作用域中。这样在切换页面后再返回当前页面时,你可以从服务或根作用域中获取之前保存的过滤条件并重新应用到过滤器中。具体做法如下:

    1.创建一个服务或者在根作用域中定义一个变量来存储过滤条件。

    app.service('filterService', function() {
      var filterCondition = {};
    
      this.getFilter = function() {
        return filterCondition;
      };
    
      this.setFilter = function(filter) {
        filterCondition = filter;
      };
    });
    

    或者在根作用域中定义一个变量:

    app.run(function($rootScope) {
      $rootScope.filterCondition = {};
    });
    

    2.在过滤器中使用存储的过滤条件。

    <input type="text" ng-model="filterCondition.filterText" />
    <div ng-repeat="item in items | filter:filterCondition">{{ item }}</div>
    

    3.在切换页面和返回页面时,将过滤条件保存到服务中或者根作用域的变量中。

    app.controller('PageController', function($scope, filterService) {
      $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        filterService.setFilter($scope.filterCondition);
      });
    
      $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
        $scope.filterCondition = filterService.getFilter();
      });
    });
    

    或者在根作用域中使用:

    app.controller('PageController', function($scope, $rootScope) {
      $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
        $rootScope.filterCondition = $scope.filterCondition;
      });
    
      $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
        $scope.filterCondition = $rootScope.filterCondition;
      });
    });
    

    这样,在页面切换后再返回当前页面时,过滤条件就会保留下来,并且自动应用到过滤器中。

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 10月18日
  • 创建了问题 10月10日