用ng-repeat过滤

时间:2018-09-24 15:41:46

标签: javascript html angularjs

我正在尝试使用名为angularJs的{​​{1}} 指令创建过滤器,该过滤器的工作方式如下: 当您在数组中单击ng-repeat过滤器中包含checkbox的项目时,我正在使用一个函数进行过滤,我认为有一种无需太多代码的更好方法。

offers
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;
        }
    };

});

1 个答案:

答案 0 :(得分:1)

您可以将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>