Angular JS-将Javascript过滤逻辑应用于Angular Filter [英] Angular JS - Apply Javascript filtering logic to Angular Filter

查看:39
本文介绍了Angular JS-将Javascript过滤逻辑应用于Angular Filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题来自在Javascript中,我使用此代码是为了进行过滤,这样我就可以在 colors 数组中显示元素时,它们也会在 cars中显示为值

In Javascript, I have this code in order to make a filtering, so that I can show the elements from the array colors just when they also appear as a value in cars

var colors = ["blue","red","pink","yellow"];

var cars = [{"brand":"Ford","color":"blue"}
           ,{"brand":"Ferrari","color":"red"}
           ,{"brand":"Rolls","color":"blue"}];

var filteredColors = colors.filter(function(color) { 
    return cars.some(function(car) { 
        return car.color === color;
    }); 
});

console.log(filteredColors);

我试图在Angular JS中应用此功能,

I have tried to apply this in Angular JS, doing this:

$scope.colors =["blue","red","pink","yellow"];

$scope.cars=[ {"brand":"Ford","color":"blue"}
           ,{"brand":"Ferrari","color":"red"}
           ,{"brand":"Rolls","color":"blue"}];

$scope.filteredColors = function() {
    var colorsvar = $scope.colors;
    var carsvar = $scope.cars;
    return colorsvar.filter(function(color) { 
        return carsvar.some(function(car) { 
            return car.color === color;
        });
    });

};

然后在视图中:

<ul>
    <li ng-repeat="n in colors | filter: filteredColors"> {{n}}
    </li>
</ul>

结果应该是

  • 蓝色
  • 红色
  • The result should be

  • blue
  • red
  • 但是无法正确过滤.在此处中查看工作中的plunkr.欢迎任何帮助,谢谢!

    But it doesn't happen to filter properly. See working plunkr here Any help will be welcome, thanks!

    推荐答案

    您可以使用以下自定义过滤器,检查DEMO

    You can use custom filter as below, check the DEMO

    演示

    var app = angular.module("myApp",[]);
    app.controller("myCtrl",function($scope){
    $scope.colors =["blue","red","pink","yellow"];
    
    $scope.cars=[ {"brand":"Ford","color":"blue"}
               ,{"brand":"Ferrari","color":"red"}
               ,{"brand":"Rolls","color":"blue"}];
    
     
    })
    app.filter('myFilter', function() {
        // the filter takes an additional input filterIDs
        return function( filterColors, inputArray) {
            var filtered = [];
           angular.forEach(inputArray,function(key,value){
                 if(filterColors.includes(key.color) && !filtered.includes(key.color)) {
                    filtered.push(key.color);
                 }
           })
           return filtered;
        };
    });

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app="myApp" ng-controller="myCtrl">
    <ul>
        <li ng-repeat="n in colors | myFilter: cars  track by $index"> {{n}}
        </li>
    </ul>
    </div>

    这篇关于Angular JS-将Javascript过滤逻辑应用于Angular Filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆