下拉列表中的角度过滤器 - 将空值分配给“全部”选择

时间:2018-02-11 12:41:32

标签: angularjs angular-filters

我使用附加过滤器的下拉列表过滤角度列表:

<div class="filter-project-type">
    <select name="project-filter" id="project-filter" ng-model="projectFilter" ng-options="project for project in projectName">
      <option value="">All</option>
    </select>
</div>
<div>
  <ul class="list" ng-show="showList">
    <task-list-element data='task' ng-repeat='task in tasksList | filter: projectFilter' ></task-list-element>
  </ul>
</div>

这是控制器代码

$scope.projectName = [];

$scope.showList = false;

$rootScope.tasksList = {};
retrieveTasksFactory.getTasksList()
.then(function (tasks) {
    var i;

    $rootScope.tasksList = tasks;
    if (tasks.length > 0) $scope.showList = true;

    // I am filling project's filter with values
    for (i = 0; i < $rootScope.tasksList.length; i++) {
        var temp = $rootScope.tasksList[i].project;
        if ($scope.projectName.indexOf(temp) == -1) {
            $scope.projectName.push(temp);
        }
     }
}, function (error) {
    console.error(error);
})

从填充的projectFilter中检索tasksList的值,它们可以正常工作。但是,我想在名为All的下拉过滤器中再添加一个值,以重置过滤器,以便tasksList中的所有元素都可见。 我尝试通过为All添加默认选项值来解决这个问题,但是由于一旦更改了下拉列表的值,它就会失效,All值就会消失。有没有人想出这个问题的解决方案。将''添加到projectName数组也不起作用,因为它在下拉菜单中给出了一个空白选项值。

此致

1 个答案:

答案 0 :(得分:0)

试试这个。将“全部”添加到您的projectName列表中。然后编写一个过滤函数来过滤tasksList。像这样:
HTML:

<div class="filter-project-type">
    <select name="project-filter" id="project-filter" ng-model="projectFilter" ng-options="project for project in projectName">
    </select>
</div>
<div>
  <ul class="list" ng-show="showList">
    <task-list-element data='task' ng-repeat='task in tasksList | filter: filterTaskList' ></task-list-element>
  </ul>
</div>

JS:

$scope.projectName = ['All'];
$scope.showList = false;
$scope.projectFilter = "All";
$rootScope.tasksList = {};

retrieveTasksFactory.getTasksList()
.then(function (tasks) {
    var i;

    $rootScope.tasksList = tasks;
    if (tasks.length > 0) $scope.showList = true;

    // I am filling project's filter with values
    for (i = 0; i < $rootScope.tasksList.length; i++) {
        var temp = $rootScope.tasksList[i].project;
        if ($scope.projectName.indexOf(temp) == -1) {
            $scope.projectName.push(temp);
        }
     }
}, function (error) {
    console.error(error);
});

$scope.filterTaskList = function(value, index, array) {
    if($scope.projectFilter == "All") {
        return true;
    } else if(value.project.indexOf($scope.projectFilter) != -1){
        return true;
    } else {
        return false;
    }
}

我没有执行此操作,但我认为它会起作用。希望这会有所帮助。