Search code examples
javascriptangularjsreturnindexofangularjs-filter

javascript if not empty element add function return


I want filter mysql with angularjs.

my fiddle

when you check tv button and click submit. (tv button values ​​= 2) angularjs filter find 2 in the amenities column. this is working. but when the TV and CABLE TV check and click submit filter is not working. Because my filter code is bad.

$scope.am_en = function()
{
$scope.ot_Filter = function (location) {
return location.amenities.indexOf(1)==0;
};
}

how to change this line indexOf(1)

this get one value indexOf(1) i want multiple value indexOf('1,7,9,11') Indexof may be another method ?

Html:

<input type="checkbox" name="more_filter[]" value="1" id="map-search-amenities-1" ng-checked="false">
<input type="checkbox" name="more_filter[]" value="2" id="map-search-amenities-2" ng-checked="false">
..vs
<button id="more_filter_submit" ng-click="am_en();">Submit</button>

I try this but not working:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

$scope.am_en = function(){
$scope.ot_Filter = function (location) {
var xC = $(".hosting_amenities input:checkbox:checked").map(function(){return $(this).val();}).get();
var xxc = "["+xC+"]";
var k1 = xxc.indexOf(1)!==-1;
var k2 = xxc.indexOf(2)!==-1;
var k3 = xxc.indexOf(3)!==-1;
...

var zz1 = location.amenities.indexOf(1)==0;
var zz2 = location.amenities.indexOf(2)==0;
var zz3 = location.amenities.indexOf(3)==0;
...

return zz1 || zz2 || zz3 || ...;
};
}

Description:

k1 == zz1

k2 == zz2

I want to: If k1 equals true add this phrase return : || zz1 If the element is present add return OR element

For Example 1:

if (k1 == true) ? "k1":""; 

if (k2 == true) ? "|| k2 ":"";  

if (k3 == true) ? "|| k3 ":"";

return k1 || k3;

For Example 2:

k1 == false; 

k2 == true; 

k3 == true;

k4 == true;

return k2 || k3 || k4;


Solution

  • Based on your response to my restatement (yes, true), here you go:

    let rooms = [ 
     { name : 'Room1', amenities : '1,3' },
     { name : 'Room2', amenities : '2,4' },
     { name : 'Room3', amenities : '1,2,3' },
     { name : 'Room4', amenities : '2,3,4' }
     ];
    
     let amenities = [ 
        { id : '1', name : 'Amenity1' },
        { id : '2', name : 'Amenity2' },
        { id : '3', name : 'Amenity3' },
        { id : '4', name : 'Amenity4' },
        ];
    
     function getAmenities ( room ) {
    
        // Turn the room amenity ids into an array
        let ids_array = room.amenities.split ( ',' );
    
        // Filter the amenities table to get the array of amenities for this room
        return amenities.filter ( x => {
            return ( ids_array.indexOf ( x.id ) !== -1 );
        } );
     }
    
     // Show amenities for a given room
     rooms.forEach ( x => { console.log ( getAmenities ( x ) ) } )