gpt4 book ai didi

javascript - Angular : how to hide DOM element based on the number of filtered elements in model?

转载 作者:行者123 更新时间:2023-11-30 17:01:24 25 4
gpt4 key购买 nike

这是一个包含用户列表的简单 Controller :

<script type="text/javascript">
angular.module('project', [])
.controller('UsersController', ['$scope', function ($scope) {
$scope.users = [
{ text: 'User 1', done: true, extension: 123 },
{ text: 'Another user', done: false, extension: 456 }];
}]);

$scope.selectedUsers = function () {
var results = [];
for (i = 0; i < $scope.users.length; i++) {
if ($scope.users[i].done) {
results.push($scope.users[i]);
}
}
return results;
};
</script>

还有一个简单的 HTML,它只为每个用户显示一个复选框,如果没有选择用户,则显示一条消息以选择某些内容。

<div ng-app="project" ng-controller="UsersController">

<input type="checkbox" ng-repeat="user in users" ng-model="user.done" id="selectUser{{$index}}" />

<div ng-hide="selectedUsers().length">Select something</div>
</div>

代码有效,但看起来有点丑。

是否有更简单的方法来获得相同的结果?

最佳答案

您可以简单地根据 done 属性筛选用户集并检查它的长度。

<div ng-hide="(users | filter:{done:true}).length">Select something</div>  

angular.module('project', [])
.controller('UsersController', ['$scope', function ($scope) {
$scope.users = [
{ text: 'User 1', done: true, extension: 123 },
{ text: 'Another user', done: false, extension: 456 }];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="project" ng-controller="UsersController">
<input type="checkbox" ng-repeat="user in users" ng-model="user.done" id="selectUser{{$index}}" />
<div ng-hide="(users | filter:{done:true}).length">Select something</div>
</div>

关于javascript - Angular : how to hide DOM element based on the number of filtered elements in model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com