按下拉列表和文本框Angular进行过滤

时间:2014-06-03 14:50:57

标签: javascript angularjs

我有一个带有布尔属性的对象数组。我需要一个三阶段的下拉菜单,它会显示所有内容,显示有效状态(那些true作为属性名称)并显示垃圾(那些false作为属性名称)。在初始页面加载时,默认视图只需要true,如果用户选择show all,则显示true和false值,如果显示垃圾,则只显示false值。我目前只加载显示的真值,但是当我从下拉列表中更改值时,下拉列表中的所有值都将被删除。 plunkr

JS

var app = angular.module('plunker', []);



app.controller('FilterController',function($scope){
    $scope.data = [{
        name: 'darrin',
        markedForDelete:true
    },{
        name: 'megan',
        markedForDelete: true

    },{
        name: 'kim',
        markedForDelete:false
    },{
        name: 'winky',
        markedForDelete: false
    }];

    //show all should show both true and false
    //show active should only show true
    //show trash should only show false
    $scope.filterOptions = [{
        name: 'Show all'

    },{
        name: 'Show active'
    },{
        name: 'Show trash'
    }];
    $scope.customFilter = function(data){
        if(data.markedForDelete){
            return true;
        }
        if(!data.markedForDelete){
            return false;
        }
    }
    $scope.name = "Darrin";
})

HTML

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.0.x" src="http://code.angularjs.org/1.0.7/angular.min.js" data-semver="1.0.7"></script>
  <script src="app.js"></script>
</head>

<body>
  <div ng-controller="FilterController">
    <input type="text" ng-model="searchText" />
    <select ng-model="filterOptions" ng-options="f.name for f in filterOptions"></select>
    <div ng-repeat="d in data | filter:customFilter ">{{d.name}}</div>

  </div>
</body>

</html>

这样做的最佳方式是什么,为什么当我对下拉列表进行更改时,它的值会被删除?

1 个答案:

答案 0 :(得分:1)

有几件事情有误。首先,您需要在某处存储选定的过滤器选项。

//Default to first option.
$scope.selectedFilterOption = $scope.filterOptions[0];

HTML

<select ng-model="selectedFilterOption" ng-options="f.name for f in filterOptions"></select>

下一个问题是您的自定义过滤器未考虑所选过滤器。把它改成这样的东西:

$scope.customFilter = function(data) {
    if ($scope.selectedFilterOption.name == 'Show all')
      return true;
    else if ($scope.selectedFilterOption.name == 'Show active' && data.markedForDelete == false)
      return true;
    else if ($scope.selectedFilterOption.name == 'Show trash' && data.markedForDelete == true)
      return true;
    else
      return false;
  }

Plunker