Angular Js - Apply Javascript Filtering Logic To Angular Filter
This question comes from this one 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 a
Solution 1:
You can use custom filter as below, check the DEMO
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 filterIDsreturnfunction( 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;
};
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp"ng-controller="myCtrl"><ul><ling-repeat="n in colors | myFilter: cars track by $index"> {{n}}
</li></ul></div>
Solution 2:
No need to call a filter. just call the function inside the ng-repeat
<ling-repeat="n in filteredColors()"> {{n}}
</li>
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"}];
$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;
});
});
};
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp"ng-controller="myCtrl"><ul><ling-repeat="n in filteredColors()"> {{n}}
</li></ul></div>
Post a Comment for "Angular Js - Apply Javascript Filtering Logic To Angular Filter"