在使用Angular js的过滤器的时候,如果在当前页面输入过滤条件,进入新页面再返回当前页面的时候,怎么能保留刚刚的过滤条件?
18条回答 默认 最新
关注获得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; }); });这样,在页面切换后再返回当前页面时,过滤条件就会保留下来,并且自动应用到过滤器中。
解决 无用评论 打赏 举报 编辑记录