[英]Filter with ng-repeat
I'm trying to make a filter with the angularJs
directive called ng-repeat
the filter works as follows: When you click on the checkbox
filters in an array the items that have offers
, I'm using a function to filter, I think there is a better way to do it without so much code. 我正在尝试使用名为
ng-repeat
的angularJs
指令制作一个过滤器,该过滤器的工作方式如下:当您单击数组中具有offers
的项的checkbox
过滤器时,我在使用函数进行过滤,我认为这是没有太多代码的更好方法。
var app = angular.module('myApp', []); app.controller('myCtrl', function($scope, $http, $document) { $scope.items = [ { id: 0, description: "Primer Item 1", offers: [ { id: 0, name: "Casa" } ] }, { id: 1, description: "Segundo Item 2" }, { id: 2, description: "Tercer Item 3" }, { id: 3, description: "Cuarto Item 4" }, { id: 4, description: "Quinto Item 5" }, { id: 5, description: "Sexto Item 5", offers: [ { id: 1, name: "Bodega" } ] }, { id: 6, description: "Septimo Item 6" }, { id: 7, description: "Octavo Item 7" }, { id: 8, description: "Noveno Item 8" }, { id: 9, description: "Decimo Item 9" } ]; $scope.filterItem = function() { if (!$scope.itemOffer){ $scope.filterOffer = function(item) { return item.offers && item.offers.length > 0; }; $scope.itemOffer = true; } else { $scope.filterOffer = function(item) { return item; }; $scope.itemOffer = false; } }; });
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> </head> <body ng-app="myApp" ng-controller="myCtrl"> <input type="checkbox" name="filter" value="propertyOffer" ng-model="propertyOffer" ng-click="filterItem()">Item with offert <div ng-repeat="item in items | filter: filterOffer track by $index"> {{ item }} </div> </body> </html>
You can use ng-if with the ng-repeat directive to filter items containing offers at will : 您可以将ng-if与ng-repeat指令一起使用,以随意过滤包含商品的项目:
JS CODE JS代码
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $document) {
$scope.offersOnly = false;
$scope.items = [
// Your items
];
});
HTML CODE HTML代码
<body ng-app="myApp" ng-controller="myCtrl">
<input type="checkbox" ng-model="offersOnly" ng-true-value="true" ng-false-value="false"/>
<div ng-repeat="item in items" ng-if="!offersOnly">
{{item}}
</div>
<div ng-repeat="item in items" ng-if="offersOnly && item.offers">
{{item}}
</div>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.