Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /****************************************************************************************************************
- *
- *
- * USED CAR SEARCH in Angular
- * =========================
- * @requires: jquery
- * @requires: lodash
- *
- *****************************************************************************************************************/
- // Initialise App
- var usedCarSearchApp = angular.module('usedCarSearchApp', ['carDataModule', 'directivesModule', 'pasvaz.bindonce']);
- /*********************************************************
- *
- * Controller
- *
- ********************************************************/
- usedCarSearchApp.controller('usedCarCtrl', function ($scope, $filter, $timeout, $interval, CarData, filterFilter) {
- $scope.loadingCars = 0;
- /**
- * Store URL
- */
- var url = window.location.pathname.split("/");
- url.shift();
- $scope.url = {
- fullpath: window.location.pathname,
- s1: url[0],
- s2: url[1],
- s3: url[2],
- s4: url[3],
- s5: url[4],
- }
- if( $scope.url.s3 !== undefined){
- var text = $scope.url.s2.split("-");
- $scope.keyword = true;
- $scope.fullTextSearch = text.join(" ");
- }
- /**
- * Fetch cars from the database and
- * then fill cars, filterOptions,
- * price dropdowns and mileage dropdowns
- */
- CarData.loadCars().then(function(cars){
- cars.sort(function(a,b){
- //return a.price - b.price;
- var first, second;
- first = a.alt_price ? Math.min(+a.alt_price, +a.price) : +a.price;
- second = b.alt_price ? Math.min(+b.alt_price, +b.price) : +b.price;
- return first - second;
- });
- cars.map(function(x){
- //console.log(x.make + " " + x.model +" " + x.price + " " + x.alt_price );
- //console.log( typeof(x.price) );
- //console.log($.type(x));
- });
- // First, add 20 cars to length
- //var firstSet = cars.slice(0,100);
- //var rest = cars.slice(101,cars.length);
- $scope.cars = cars;
- $scope.loadingCars = 1;
- if($scope.keyword){
- var filtered = $filter('search')(cars, $scope.fullTextSearch);
- console.log("Showing Filtered Count_____________________");
- if(filtered.length == 0){
- $scope.fullTextSearch = "";
- }
- /*filtered.map(function(a){
- console.log(a.make + " " + a.model);
- });*/
- }
- $scope.filterOptions = CarData.filters;
- fillPriceDropdowns(cars);
- fillMileageDropdowns(cars);
- fillYearDropdown(cars);
- fillMpgDropdown(cars);
- fillBodyTypes(cars);
- fillEngineSizes(cars);
- /*$timeout(function () {
- $scope.cars = $scope.cars.concat(rest);
- }, 2000);*/
- }).then(function(){
- CarData.getTaxInfo().then(function(tax){
- $scope.taxTable = tax;
- fillTaxDropdown(tax);
- }).then(function(){
- CarData.getVehicleColours().then(function(colours){
- //console.log(colours);
- $scope.coloursTable = colours;
- fillColoursDropdown(colours);
- })
- })
- })
- /**
- * Fill Price Select Boxes
- */
- function fillPriceDropdowns(cars){
- // Fill an array of all prices
- var prices = cars.map(function(x){ return x.price });
- // Get min and max prices
- var minPrice = Math.min.apply(null, prices);
- var maxPrice = Math.max.apply(null, prices);
- // Amount to round by
- var rounding = 1000;
- var minArray = [];
- var maxArray = [];
- // Get start and end for max dropdown
- var maxStart = rounding * Math.ceil(minPrice / rounding);
- var maxEnd = rounding * Math.ceil(maxPrice / rounding);
- while(maxStart <= maxEnd)
- {
- maxArray.push(maxStart);
- maxStart += 1000;
- }
- // Get start and end for min dropdown
- var minStart = 0;
- var minEnd = rounding * Math.floor(maxPrice / rounding);
- while(minStart <= minEnd)
- {
- minArray.push(minStart);
- minStart += 1000;
- }
- $scope.filterOptions.minPrice = minArray;
- $scope.filterOptions.maxPrice = maxArray;
- }
- /**
- * Fill Mileage Select Boxes
- */
- function fillMileageDropdowns(cars){
- // Fill an array of all prices
- var mileages = cars.map(function(x){ return x.mileage });
- // Get min and max prices
- var minMileage = Math.min.apply(null, mileages);
- var maxMileage = Math.max.apply(null, mileages);
- // Amount to round by
- var rounding = 10000;
- var minStart = 0;
- var minEnd = rounding * Math.floor(maxMileage / rounding);
- var maxStart = 10000;
- var maxEnd = rounding * Math.ceil(maxMileage / rounding);
- var minArray = [];
- var maxArray = [];
- while(minStart <= minEnd)
- {
- minArray.push(minStart);
- minStart += 10000;
- }
- while(maxStart <= maxEnd)
- {
- maxArray.push(maxStart);
- maxStart += 10000;
- }
- var minMileageContainer = [];
- _.each(minArray, function(item){
- var obj = {
- name: number_format(item) + " Min Miles",
- value: item
- }
- minMileageContainer.push(obj);
- });
- var maxMileageContainer = [];
- _.each(maxArray, function(item){
- var obj = {
- name: number_format(item) + " Max Miles",
- value: item
- }
- maxMileageContainer.push(obj);
- });
- $scope.filterOptions.minMileage = minMileageContainer;
- $scope.filterOptions.maxMileage = maxMileageContainer;
- }
- /**
- * Fill Year Select Box
- */
- function fillYearDropdown(cars){
- var years = cars.map(function(x){ return x.year_of_man });
- var unique = _.unique(years);
- unique = unique.sort(function(a,b){
- return b-a;
- })
- var len = unique.map(function(x){
- return new Date().getFullYear() - x;
- });
- if(len[0] === 0) { len.shift(); }
- var arrObjs = len.map(function(l){
- return {
- label: "Up To " + l + " Year",
- val: l
- }
- })
- //console.log(arrObjs);
- $scope.filterOptions.age = arrObjs;
- }
- /**
- * Fill MPG Select Box
- */
- function fillMpgDropdown(cars){
- // Get array of mpg from each car
- var mpgs = cars.map(function(x){ return x.mpg; });
- // Get unique only mpgs
- var unique = _.unique(mpgs);
- // Strip zero from the list
- unique = _.pull(unique,0);
- // Set rounding amount
- var rounding = 10;
- // Get minimum mpg value
- var minMpg = Math.min.apply(0,unique);
- // Get minimum mpg for the dropdown list of mpgs
- var mpgListMin = rounding * Math.floor(minMpg / rounding);
- //console.log(minMpg);
- //console.log(mpgListMin);
- // Get maximum mpg value
- var maxMpg = Math.max.apply(0,unique);
- //console.log("Max mpg is " + maxMpg);
- // Get maximum mpg for the dropdown list of mpgs
- var mpgListMax = rounding * Math.floor(maxMpg / rounding);
- // Dropdown List
- var out = [];
- // Generate dropdown list values
- while(mpgListMin <= mpgListMax)
- {
- out.push(mpgListMin);
- mpgListMin += 10;
- }
- // Create array of objects that have label and val
- var arrObjs = out.map(function(x){
- return {
- label: "More than " + x + " mpg",
- val: x
- }
- })
- $scope.filterOptions.mpg = arrObjs;
- }
- /**
- * Fill Body Types (Unused)
- */
- function fillBodyTypes(cars){
- // Get array of bodytypes from each car
- var bodytypes = cars.map(function(x){ return x.body_types; });
- // Get unique only mpgs
- var unique = _.unique(bodytypes);
- var arr = [];
- _.each(unique, function(item){
- var name = "";
- switch(parseInt(item,10)){
- case 0:
- name = "Hatchback";
- break;
- case 1:
- name = "Estate";
- break;
- case 2:
- name = "4x4";
- break;
- case 3:
- name = "MPV";
- break;
- case 4:
- name = "SUV";
- break;
- case 5:
- name = "Saloon";
- break;
- case 6:
- name = "Coupe";
- break;
- case 7:
- name = "Convertible";
- break;
- case 8:
- name = "Sports";
- break;
- default:
- name = "";
- break;
- }
- var obj = {
- name: name,
- value: item
- }
- arr.push(obj);
- })
- //console.log(arr);
- }
- /**
- * Fill Engine Sizes Dropdown
- */
- function fillEngineSizes(cars){
- var dropdowns = [
- {
- name: "Less Than 1L",
- value: 1
- },
- {
- name: "1L - 1.3L",
- value: 2
- },
- {
- name: "1.4L - 1.6L",
- value: 3
- },
- {
- name: "1.7L - 1.9L",
- value: 4
- },
- {
- name: "2L - 2.5L",
- value: 5
- },
- {
- name: "2.6L+",
- value: 6
- },
- ];
- $scope.filterOptions.engineSizes = dropdowns;
- }
- /**
- * Fill Tax Dropdown
- */
- function fillTaxDropdown(tax){
- var ret = [];
- tax.map(function(t){
- if(t.id < 14){
- var a = {
- name: t.standard_12m,
- value: t.band
- };
- ret.push(a);
- }
- });
- $scope.filterOptions.tax = ret;
- }
- /**
- * Fill Colours Dropdown
- */
- function fillColoursDropdown(colours){
- var ret = [];
- colours.map(function(c){
- var a = {
- name: c.name,
- value: c.bit
- };
- ret.push(a);
- });
- $scope.filterOptions.colours = ret;
- }
- /**
- * On click of the "Begin Search" button, lookup postcode in database,
- * if we do not have it, then lookup with Google Maps API
- */
- $scope.lookupPostcode = function(postcode){
- // Initialise location
- var location = {};
- // Use Data Factory to check for postcode to fetch lat/long information
- CarData.checkDatabaseForPostcode(postcode).then(function(r){
- // If not in the database
- if(r == "false"){
- fetchLocationFromGoogle(postcode);
- }else{ // Found postcode in database
- // Add location to scope
- addLocationToScope(postcode, r.lat, r.long);
- // Set scope logic to say found postcode, from Database
- $scope.postcodeFound = true;
- $scope.postcodeViaDB = true;
- $scope.postcodeViaGoogle = false;
- calculateDistances(postcode, r.lat, r.long);
- return;
- }
- })
- };
- /**
- * Fetch Location Details From Google
- */
- function fetchLocationFromGoogle(postcode){
- geocoder.geocode( {'address':postcode}, function(results,status){
- if(status == google.maps.GeocoderStatus.OK){
- // Get Location Information from the Google Maps API response
- var lat = results[0].geometry.location.lat();
- var lng = results[0].geometry.location.lng();
- //console.log(lat + " " + lng);;
- // Store location in the database
- storeLocation(postcode,lat, lng );
- // Add location to scope
- addLocationToScope(postcode, lat, lng);
- // Set scope logic to say found postcode, from Google
- $scope.postcodeFound = true;
- $scope.postcodeViaGoogle = true;
- $scope.postcodeViaDB = false;
- calculateDistances(postcode, lat, lng);
- }else{
- alert("Geocode was not successful for the following reason: " + status);
- $scope.postcodeFound = false;
- }
- });
- }
- /** Helper Function to add location details to the scope **/
- function addLocationToScope(postcode, lat, long){
- $scope.user = {
- location: {
- postcode:postcode,
- lat:lat,
- lng:long
- }
- }
- }
- function calculateDistances(postcode, lat, lng){
- lat = parseFloat(lat);
- lng = parseFloat(lng);
- var locations = _.unique($scope.cars, 'name');
- //console.log(locations);
- //var distances = [];
- /*locations.forEach(function(i){
- var dealerLat = i.latitude;
- var dealerLong = i.longitude;
- var dealerLocationObject = new LatLon(dealerLat,dealerLong);
- var customerLocationObject = new LatLon(lat,lng);
- var distance = dealerLocationObject.distanceTo(customerLocationObject);
- //console.log(distance);
- var item = {}; item[i.name] = distance;
- distances.push(item);
- })*/
- /*var distances = locations.map(function(location){
- var dealerLat = parseFloat(location.latitude);
- var dealerLong = parseFloat(location.longitude);
- var dealerLocationObject = new LatLon(dealerLat,dealerLong);
- var customerLocationObject = new LatLon(lat,lng);
- var distance = dealerLocationObject.distanceTo(customerLocationObject);
- var item = {};
- item[location.name] = distance;
- return item;
- });*/
- var distances = locations.reduce(function(distances, location){
- var dealerLat = parseFloat(location.latitude);
- var dealerLong = parseFloat(location.longitude);
- var dealerLocationObject = new LatLon(dealerLat,dealerLong);
- var customerLocationObject = new LatLon(lat,lng);
- var distance = dealerLocationObject.distanceTo(customerLocationObject);
- distance = distance * 0.62137;
- distance = Math.round(distance);
- distances[location.name] = distance;
- return distances;
- }, {})
- $scope.cars.forEach(function(car){
- car.distance = distances[car.name];
- console.log(car.distance);
- })
- var distanceSortObj = {id : 7, name : 'Distance Closest to Furthest' , "predicate" : "distance" };
- $scope.sortOptions.stores.push( distanceSortObj );
- $scope.distances = distances;
- }
- /**
- * Store location in database
- */
- storeLocation = function(postcode, lat, long){
- CarData.storeLocation(postcode, lat, long).then(function(r){
- //return r;
- })
- }
- /**
- * Check Database for Postcode -> uses publically exposed method of the Data Factory
- */
- checkDatabaseForPostcode = function(postcode){
- return CarData.checkDatabaseForPostcode(postcode);
- }
- $scope.storeSearch = function(){
- /*$scope.postcode;
- $scope.filterItem.make;
- $scope.filterItem.model;
- $scope.fullTextSearch;
- $scope.filterItem.minPrice;
- $scope.filterItem.maxPrice;
- $scope.filterItem.fuel_type;
- $scope.filterItem.transmission;
- $scope.filterItem.colour;
- $scope.sortItem.store;
- $scope.filteredData.length;
- */
- var filteredItems = [];
- angular.forEach($scope.filteredData, function(val,key){
- this.push(val.id);
- }, filteredItems);
- }
- /*$scope.$watchCollection('filterItem', function(newCollection, oldCollection){
- console.log("Triggered WATCH");
- $scope.$broadcast('Filter');
- });*/
- /*$interval(function(){
- $('.circle, .circle1').toggle();
- }, 1000, 2, true);*/
- $scope.change = function () {
- $scope.$emit('change')
- }
- $scope.$watch('filterItem', function() {
- var isFirstCycle = false;
- if($scope.filterCount == -1){
- $scope.filterCount++;
- isFirstCycle = true;
- }
- if(isFirstCycle === true) return false;
- storeSearch();
- }, true); // end watch
- $scope.runFullTextSearch = function(e){
- if (e.keyCode == 13) {
- $scope.fullTextSearch = $scope.fullTextSearchVal;
- storeSearch();
- }
- if(e.keyCode == 27){
- $scope.fullTextSearch.$rollbackViewValue();
- }
- }
- $scope.storeSearch = function(){
- $scope.fullTextSearch = $scope.fullTextSearchVal;
- storeSearch();
- }
- function storeSearch(){
- $scope.$broadcast('Filter'); // triggers the Filter event to refresh the car images so they load without scroll
- $timeout(function(){
- // Gets the filtered items into an array
- if($scope.filteredData) var filteredItems = $scope.filteredData.map(function(x){ return x.id });
- var searchData = {
- filteredCars : filteredItems,
- searchNumber : $scope.filterCount,
- filterMake : $scope.filterItem.make,
- filterModel : $scope.filterItem.model,
- filterKeyword : $scope.fullTextSearch,
- filterMinPrice : $scope.filterItem.minPrice,
- filterMaxPrice : $scope.filterItem.maxPrice,
- filterMinMileage : $scope.filterItem.minMileage,
- filterMaxMileage : $scope.filterItem.maxMileage,
- filterAge : $scope.filterItem.age,
- filterMpg : $scope.filterItem.mpg,
- filterFuelType : $scope.filterItem.fuel_type,
- filterEngineSize : $scope.filterItem.engine_size,
- filterTransmission : $scope.filterItem.transmission,
- filterTax : $scope.filterItem.tax,
- filterColour : $scope.filterItem.colour,
- filterBodyType : $scope.filterItem.body_type,
- filterDoors : $scope.filterItem.doors,
- sortMethod : $scope.sortItem.store,
- resultsCount : filteredItems.length
- };
- if($scope.user !== undefined){
- console.log($scope.user.postcode);
- searchData.postcode = $scope.user.location.postcode;
- }
- // console.log(searchData);
- CarData.storeSearch(searchData).then(function(r){
- console.log(r);
- })
- }) // end timeout
- $scope.filterCount++; // Increase filter count
- }
- /**
- * Fetch Models when Make is selected
- */
- $scope.fetchModels = function(make){
- //console.log(make);
- if(make === null || make === undefined){
- $scope.modelFilterOptions = { stores: [] };
- $scope.filterItem.model = {};
- return;
- }
- CarData.fetchModels(make.name).then(function(models){
- $scope.modelFilterOptions = { stores: [] };
- angular.forEach(models, function(v){
- v.label = v.model;
- $scope.modelFilterOptions.stores.push(v);
- })
- })
- }
- // Contains the sorting options
- $scope.sortOptions = {
- stores: [
- {id : 1, name : 'Price Lowest to Highest', "predicate" : "price" },
- {id : 2, name : 'Price Highest to Lowest' , "predicate" : "-price"},
- {id : 3, name : 'Mileage Lowest to Highest' , "predicate" : "mileage" },
- {id : 4, name : 'Mileage Highest to Lowest' , "predicate" : "-mileage" },
- {id : 5, name : 'MPG Highest to Lowest' , "predicate" : "-mpg" },
- {id : 6, name : 'Age Newest to Oldest' , "predicate" : "-year_of_man" },
- ]
- };
- // Mapped to the model to sort
- $scope.sortItem = {
- store: $scope.sortOptions.stores[0]
- };
- $scope.getMinPrice = function(priceData){
- if(!priceData) { return;}
- var prices = priceData.map(function(x){ return x.price });
- var min = Math.min.apply(null, prices);
- return min;
- }
- $scope.getMaxPrice = function(priceData){
- if(!priceData) { return;}
- var prices = priceData.map(function(x){ return x.price });
- var max = Math.max.apply(null, prices);
- return max;
- }
- $scope.minPriceFilter = function( min ){
- return function(item){
- if(!min)
- {
- return true;
- }
- if(item.price >= min)
- {
- return true;
- }
- }
- }
- $scope.maxPriceFilter = function( max ){
- return function(item){
- if(!max)
- {
- return true;
- }
- if(item.price <= max)
- {
- return true;
- }
- }
- }
- /**
- * When the min price is changed, the lowest max
- * price changes accordingly so that it is always
- * 10000 higher than the min price dropdown.
- */
- $scope.maxPriceMinFilter = function ( maxPrice ){
- return function(item){
- if(!maxPrice)
- {
- return true;
- }
- if(item > maxPrice)
- {
- return true;
- }
- }
- }
- $scope.minMileageFilter = function( min ){
- return function(item){
- if(!min)
- {
- return true;
- }
- if(item.mileage >= min)
- {
- return true;
- }
- }
- }
- $scope.maxMileageFilter = function( max ){
- return function(item){
- if(!max)
- {
- return true;
- }
- if(item.mileage <= max)
- {
- return true;
- }
- }
- }
- /**
- * When the min mileage is changed, the lowest
- * max mileage changes accordingly so that it is
- * always 10000 higher than the min mileage dropdown.
- */
- $scope.maxMileageMinFilter = function ( mil ){
- return function(item){
- if(!mil)
- {
- return true;
- }
- if(item > mil)
- {
- return true;
- }
- }
- }
- $scope.ageFilter = function ( age ){
- return function(item){
- if(!age){
- return true;
- }
- if(new Date().getFullYear() - item.year_of_man <= age){
- return true;
- }
- }
- }
- $scope.mpgFilter = function ( mpg ){
- return function(item){
- if(!mpg){
- return true;
- }
- if(item.mpg >= mpg){
- return true;
- }
- }
- }
- $scope.engineSizeFilter = function ( option ){
- return function(item){
- if( $.isEmptyObject(option) || option === null ){
- return true;
- }
- item = item.engine_size;
- switch(option){
- case 1:
- return item < 1000;
- break;
- case 2:
- return item >= 1000 && item <= 1349;
- break;
- case 3:
- return item >= 1350 && item <= 1649;
- case 4:
- return item >= 1650 && item <= 1949;
- case 5:
- return item >= 1950 && item <= 2599;
- case 6:
- return item >= 2600;
- } // end switch
- }
- }
- $scope.taxFilter = function( tax ){
- return function(item){
- if( !tax || tax === null ){
- return true;
- }
- var row = _.where($scope.taxTable, { band: tax });
- var r = row[0];
- var min = r.value_low !== null ? +r.value_low : 0;
- var max = r.value_high !== null ? +r.value_high : 9999;
- if(item.co2 <= max){
- return true;
- }
- }
- }
- /* ########################### COUNT FUNCTIONS ############################ */
- $scope.getFuelTypeCount = function(fuel_type){
- var newData = $filter('filter')($scope.filteredData,{fuel_type: fuel_type});
- return newData.length;
- }
- $scope.getTransmissionCount = function(transmission){
- var newData = $filter('filter')($scope.filteredData,{transmission: transmission});
- return newData.length;
- }
- $scope.getColourCount = function(colour){
- var colourNewData = $filter('filter')($scope.filteredData,{colour_categories: colour});
- console.log(colourNewData);
- return colourNewData.length;
- }
- $scope.getDoorsCount = function(doors){
- var newData = $filter('filter')($scope.filteredData,{doors: doors});
- return newData.length;
- }
- /**
- * Clear Filters
- */
- $scope.clearFuelTypes = function(){
- $scope.filterItem.fuel_type = [];
- }
- $scope.clearTransmissions = function(){
- $scope.filterItem.transmission = [];
- }
- $scope.clearColours = function(){
- $scope.filterItem.colour = [];
- }
- $scope.clearDoors = function(){
- $scope.filterItem.doors = [];
- }
- /**
- * Stores the items to be filtered by
- */
- $scope.filterItem = {fuel_type: [], colour: [], transmission: [], doors: [], body_type: [], engine_size: []};
- $scope.filterCount = -1;
- /************************* HELPERS **************************/
- /**
- * Same as PHP number_format
- * Call the phpjs number_format function
- */
- $scope.number_format = function(num, decimals,dec_point, seperator){
- return number_format(num, decimals, dec_point, seperator);
- }
- /**
- * Loop through array and convert all strings to int
- * @param {Array} arr Array of Strings
- * @return {Array} Array of Integers
- */
- $scope.arrayStrToNum = function(arr){
- var numbers = arr.map(function(num){
- return parseInt(num, 10);
- });
- return numbers;
- }
- /**
- * Generate URL link to specific used car
- * @param {[type]} car [description]
- * @return {[type]} [description]
- */
- $scope.generateHref = function(car){
- if(!car) { return; }
- var link = "http://www.sandicliffe.co.uk/used-car/";
- var make = car.make.replace(" ","-");
- make = make.toLowerCase();
- var model = car.model.replace(" ","-");
- model = model.toLowerCase();
- var der = car.derivative;
- der = der.replace(" ","-");
- der = der.toLowerCase();
- var reg = car.reg_number;
- reg = reg.replace(" ","-");
- reg = reg.toLowerCase();
- link += make + "/" + model + "/" + der + "/" + reg;
- return link;
- }
- $scope.getDisplayPrice = function(item){
- // If no item or item price or item alt_price, return
- if(!item) { return; }
- var price = parseInt(item.price,10);
- var alt_price = parseInt(item.alt_price,10);
- // If alt_price is lower than price
- if(alt_price < price){
- // If alt_price is lower than 2
- if(alt_price < 2){
- return number_format(price);
- }else{
- return number_format(alt_price);
- }
- }else{
- return number_format(price);
- }
- }
- $scope.charLimit = function(str, n, useWordBoundary){
- var toLong = str.length>n,
- s_ = toLong ? str.substr(0,n-1) : str;
- s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
- return toLong ? s_ + '...' : s_;
- };
- $scope.carFilter = function(){
- return function(item){
- // If MAKE is set
- if( $scope.filterItem.make ){
- var filterMake = $scope.filterItem.make.name.toLowerCase();
- if(filterMake != item.make.toLowerCase() ){
- return false;
- }
- // If MODEL is set
- if( $scope.filterItem.model ){
- var filterModel = $scope.filterItem.model.model.toLowerCase();
- if( filterModel != item.model.toLowerCase()){
- return false;
- }
- }
- }
- if( $scope.filterItem.body_type ){
- var filterBodytypes = $scope.arrayStrToNum($scope.filterItem.body_type);
- if( !_.contains(filterBodytypes, item.body_types) ){
- return false;
- }
- }
- return true;
- }
- }
- $scope.resetAllFilters = function(){
- $scope.filterItem = {fuel_type: [], colour: [], transmission: [], doors: [], body_type: [], engine_size: []};
- }
- }); // end of controller
- /**
- * Directive: checkList
- */
- usedCarSearchApp.directive('checkList', function() {
- return {
- scope: {
- list: '=checkList',
- value: '@'
- },
- link: function(scope, elem, attrs) {
- var handler = function(setup) {
- var checked = elem.prop('checked');
- var index = scope.list.indexOf(scope.value);
- if (checked && index == -1) {
- if (setup) elem.prop('checked', false);
- else scope.list.push(scope.value);
- } else if (!checked && index != -1) {
- if (setup) elem.prop('checked', true);
- else scope.list.splice(index, 1);
- }
- };
- var setupHandler = handler.bind(null, true);
- var changeHandler = handler.bind(null, false);
- elem.on('change', function() {
- scope.$apply(changeHandler);
- });
- scope.$watch('list', setupHandler, true);
- }
- };
- });
- /**
- * Filter: multiFilter
- *
- * @param {array/object} collection The original data set to be filtered
- * @param {string} property The key to filter by
- * @param {array} values The values to filter by
- *
- */
- usedCarSearchApp.filter('multiFilter',function(){
- return function(collection, property, values) {
- if(values.length === 0)
- {
- return collection;
- }
- return _.filter(collection, function(item) {
- return _.contains(values, item[property]);
- });
- }
- })
- // Unique filter - to extract unique values from a set of data
- //https://github.com/angular-ui/ui-utils/blob/master/modules/unique/unique.js
- usedCarSearchApp.filter('unique', ['$parse', function ($parse) {
- return function (items, filterOn) {
- if (filterOn === false) {
- return items;
- }
- if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
- var newItems = [],
- get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item; };
- var extractValueToCompare = function (item) {
- return angular.isObject(item) ? get(item) : item;
- };
- angular.forEach(items, function (item) {
- var isDuplicate = false;
- for (var i = 0; i < newItems.length; i++) {
- if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
- isDuplicate = true;
- break;
- }
- }
- if (!isDuplicate) {
- newItems.push(item);
- }
- });
- items = newItems;
- }
- return items;
- };
- }]);
- usedCarSearchApp.filter('num', function() {
- return function(input) {
- return parseInt(input, 10);
- }
- });
- /**
- * Filter: multiFilter for BODY TYPES
- *
- * @param {array/object} collection The original data set to be filtered
- * @param {string} property The key to filter by
- * @param {array} values The values to filter by
- *
- */
- usedCarSearchApp.filter('multiFilterBodytype',function(){
- return function(collection, property, values) {
- if(values.length === 0) {
- return collection;
- }
- /*if( _.contains(values, "2") && !_.contains(values,"4") ) {
- values.push("4");
- }else {
- _.pull(values, "4");
- }*/
- return _.filter(collection, function(item) {
- return _.contains(values, item[property]);
- });
- }
- })
- /**
- * Filter: multiFilter for ENGINE SIZES
- *
- * @param {array/object} collection The original data set to be filtered
- * @param {string} property The key to filter by
- * @param {array} values The values to filter by
- *
- */
- usedCarSearchApp.filter('multiFilterEngineSize',function(){
- return function(collection, property, values) {
- if(values.length === 0) {
- return collection;
- }
- if( _.contains(values, "1") ) {
- if(item[property] < 1000) return true;
- }else if( _.contains(values, "2") ) {
- }else if( _.contains(values, "3") ) {
- }else if( _.contains(values, "4") ) {
- }else if( _.contains(values, "5") ) {
- }else if( _.contains(values, "6") ) {
- }
- /*return _.filter(collection, function(item) {
- return _.contains(values, item[property]);
- });*/
- }
- });
- usedCarSearchApp.filter('search', function($filter){
- return function(items, text){
- if (!text || text.length === 0)
- return items;
- // split search text on space
- var searchTerms = text.split(' ');
- // search for single terms.
- // this reduces the item list step by step
- searchTerms.forEach(function(term) {
- if (term && term.length)
- items = $filter('filter')(items, term);
- });
- return items
- };
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement