抱歉,如果这个问题以前已经解决过,但我找不到答案。
我正在尝试根据单选按钮上的选择对 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/