簡體   English   中英

用ng-repeat過濾

[英]Filter with ng-repeat

我正在嘗試使用名為ng-repeatangularJs 指令制作一個過濾器,該過濾器的工作方式如下:當您單擊數組中具有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> 

您可以將ng-if與ng-repeat指令一起使用,以隨意過濾包含商品的項目:

JS代碼

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $document) {
    $scope.offersOnly = false;
    $scope.items = [
        // Your items
    ];
});

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM