chgbj 2023-10-10 05:13 采纳率: 6.7%
浏览 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日

悬赏问题

  • ¥15 Windows Script Host 无法找到脚本文件"C:\ProgramData\Player800\Cotrl.vbs”
  • ¥15 matlab自定义损失函数
  • ¥15 35114 SVAC视频验签的问题
  • ¥15 impedancepy
  • ¥15 求往届大挑得奖作品(ppt…)
  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图