javascript - 如何根据 true false 条件过滤 ng-repeat 数据

标签 javascript html angularjs angularjs-directive

抱歉,如果这个问题以前已经解决过,但我找不到答案。

我正在尝试根据单选按钮上的选择对 ng-repeat 进行排序, 但我根本不知道如何隐藏和显示 ng-repeat 中的项目。

一个例子:

html:

<form>
 <label><input type="radio" name="generic" />all</label>
 <label><input type="radio" name="generic" />offline</label>
</form>

<div ng-repeat="channel in controller.channelArray>
 <div>{{channel.name}}</div>
</div>

JavaScript:

channelArray = [];
pushStreams();

function pushStreams(data) {
 channelArray.push(data)
}

现在,这只是一个示例,我还没有测试过这段代码,但它可以在我的真实代码中运行。 我只是想知道,假设数据包含一个为假或真的状态变量,如何显示所有内容(假和真)以及如果我选择离线单选按钮如何过滤掉真值。

希望这足够清楚,谢谢!

最佳答案

为此,您可以使用 ng-if 指令。

The ng-if directive removes or recreates a portion of the DOM tree based on an {expression}.

<div ng-repeat="channel in channels">
     <div ng-if="validate(channel)">{{channel.name}}</div>
</div>

function TodoCtrl($scope) {
   $scope.check='All';
   $scope.channels=[{
     name:'a',
     status:true
   },{
     name:'b',
     status:false
   },{
     name:'c',
     status:false
   },{
      name:'d',
     status:true
   }];
   
   $scope.validate=function(channel){
      switch($scope.check){
        case 'All':
           return true;
        case 'Offline':
           return !channel.status;
        case 'Online':
           return channel.status;
      }
   }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl"> 
     <label><input type="radio" name="generic" ng-model="check" value="All" />all</label>
     <label><input type="radio" name="generic" ng-model="check" value="Offline" />offline</label>
     <label><input type="radio" name="generic" ng-model="check" value="Online" />online</label>
    <div ng-repeat="channel in channels">
         <div ng-if="validate(channel)">{{channel.name}}</div>
     </div>
  </div>
</div>

关于javascript - 如何根据 true false 条件过滤 ng-repeat 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42364526/

相关文章:

html - 如何在子div之间划分父div的高度

html - 如何以 Tiles 格式而不是表格格式显示 Angular 数据

Javascript检测文本区域中的滚动条

javascript - HTML - 下拉列表的 selectedindexchanged 第二次不起作用

javascript - 如何根据cookie值从页面中删除元素?

jquery - 在 jquery 中搜索

javascript - Express JS 中的 POST 函数

javascript - 灯箱、CSS 和 JavaScript

javascript - 带有 onkeyup 事件的输入标签用于建议数据列表,不适用于键盘上/下箭头键

javascript - 在 jasmine 中调用 $scope 方法