Utilizing AngularJS to filter prices within a specific range using a button

I am new to using angularjs and I am working on implementing a price range filter with nouislider for a list of products with different prices. I want the filtering to happen only after the user clicks on the filter button. Below is the HTML code for my "slide filter":

            <section class="filter-section">
                <h3>Price</h3>
              <form method="get" name="price-filters">
                <span ng-click="price_slider.start = [180, 1400]" class="clear" id="clearPrice" >Clear</span>
                <div class="price-slider">
                    <div id="price-range" ya-no-ui-slider="price_slider"></div>
                  <div class="values group">
                    <!--data-min-val represent minimal price and data-max-val maximum price respectively in pricing slider range; value="" - default values-->
                    <input class="form-control" name="minVal" id="minVal" type="text" ng-model="price_slider.start[0]">
                    <span class="labels">€ - </span>
                    <input class="form-control" name="maxVal" id="maxVal" type="text" ng-model="price_slider.start[1]">
                    <span class="labels">€</span>
                  </div>
                  <input class="btn btn-primary btn-sm" type="submit" ng-click="priceFiltering('filter')" value="Filter">
                </div>
              </form>
            </section>

This is the code for the price slider in my controller:

$scope.price_slider = {
        start: [180, 1400],
        connect: true,
        step: 1,
        range: {
            min: 10,
            max: 2500
        }
    }; 

And here is the filter function in my controller:

    $scope.priceFiltering = function(command){
    if (command === "filter"){
        $scope.pricefilter = function (product) {
            if ((product.price <= $scope.price_slider.start[1])&&(product.price >= $scope.price_slider.start[0])){
                return product;
            }
        };
        command = "nofilter";
    }   
}

The filter is applied using ng-repeat like this:

<div ng-repeat="product in products | filter:pricefilter  | orderBy:propertyName:reverse">...
</div>

Currently, the filter works as expected initially where the user selects a price range on the slider (e.g., min 800€ and max 1000€) and clicking the filter button displays the correct products. However, when the user moves the slider again, the filter immediately updates the products. I would like the filtering to occur only when the filter button is clicked. I believe I'm close to achieving this behavior but need some assistance. Can anyone help me with this?

Answer №1

To make the filter function work properly, a slight adjustment is needed.

Instead of directly referencing $scope.price_slider.start[0] and $scope.price_slider.start[1] in the filter, you should assign these values to other scopes within the priceFiltering function and then use those scopes in the filter.

Take a look at the revised code below:

$scope.priceFiltering = function(){
    $scope.minPrice = $scope.price_slider.start[0];
    $scope.maxPrice = $scope.price_slider.start[1];

    $scope.pricefilter = function (product) {
        if ((product.price <= $scope.maxPrice) && (product.price >= $scope.minPrice)){
            return product;
        }
    };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues when attempting to create a service worker in a Vue.js application using Workbox's injectManifest feature

I'm attempting to utilize vue.js's capabilities for progressive web apps by creating a customized service worker using workbox. However, every time I try to build the app, I encounter the following error: AssertionError [ERR_ASSERTION]: swSrc mus ...

Enhancing TypeScript - Managing Variables within Namespace/Scope

Why is the console.log inside the function correctly logging the object, but after the function returns it logs undefined, failing to update the variable? In addition, when using this within testNameSpace, it returns window. Why is that? namespace testNa ...

Is it possible to use D3 for DOM manipulation instead of jQuery?

After experimenting with d3 recently, I noticed some similarities with jquery. Is it feasible to substitute d3 for jquery in terms of general dom management? This isn't a comparison question per se, but I'd appreciate insights on when it might b ...

What could be causing the ERROR TypeError in an Angular form where "_co.service.formData" is undefined?

My attempt to create a form in Angular 7 has resulted in an error message: ERROR TypeError: "_co.service.formData is undefined" Here is the HTML code for the component: <form (sumbit)="signUp(form)" autocomplete="off" #form="ngForm"> <div clas ...

How do I delete an attached file in an input document? (Firefox)

Is there a way to smoothly remove an attachment selected in the <input type="file"> element? In Firefox, removing an already selected attachment can be tricky. Simply deleting the name or trying to click open may not work. An additional solution mi ...

Retrieve the id of an element from a JSON object

Dealing with quotes, single or double, can sometimes pose a challenge. I am working on a JavaScript function that sends data to a PHP file and receives a JSON response. Everything seems to be functioning correctly, except for the part where I need to out ...

A beginner's guide to setting up CORS on Vert.x 2.x

I've been attempting to perform cross-domain requests using Angularjs 1.4.5, but so far, I haven't been able to make it work. I've configured $httpprovider as follows: .config(['$httpProvider', function($httpProvider) { $h ...

Implementing CORS for controlling the origin of post requests

I am currently in the process of setting up a route at sub.domain.com/route. On domain.com, I have an Angular app that sends a post request to that endpoint. My main concern is whether I need to implement CORS on sub.domain.com/route to restrict post requ ...

What is preventing me from successfully retrieving data at times when using curl_setopt and jQuery Ajax?

In my quest to fetch data from another server, I am using the curl_setopt PHP function along with Ajax. The function I have created seems to be working fine, but sometimes when I refresh the page and the internet connection is slow, I don't receive an ...

Learn how to smoothly transition between AJAX pages by toggling a class on click for a seamless animation

I am currently working on a practice project that involves loading each page via AJAX and displaying a fadeIn, fadeOut transition using CSS animation opacity. However, I am facing an issue where the addClass and removeClass functions are not being execute ...

Tips for submitting an Ajax Form with identical Name attributes?

One part of my form consists of input fields with the same 'Name' values that will be stored as an Array. I am attempting to send these values via AJAX to PHP for updating my database. The challenge I'm facing is figuring out how to send t ...

Why does the width of my image appear differently on an iPhone compared to other devices?

I recently encountered an issue with the responsiveness of an image on my website. While it displayed correctly on Android and desktop devices, the image appeared distorted on iPhones as if the CSS width attribute was not applied properly. This problem spe ...

Exploring the powerful trio of Node.js, MySQL, and asynchronous iterative functions

Currently grappling with an iterative function in nodejs. I'm traversing through an object and checking for any attached sub-objects (imagine a star having a planet with a moon that has an orbital station with a ship). The aim is to construct an arr ...

Broaden the reach of the ajax .done function to encompass the surrounding function

It seems like my previous attempts to find a solution for the function below were unsuccessful: function countNoFilters(keyword){ keyword = typeof keyword !== 'undefined' ? keyword : "keyword="+$("#keyword-hidden").val(); var getR ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

Concealing certain elements within a loop using a "show more" button

In my PHP code, I am utilizing a foreach loop in the following manner: <div class="items"> @foreach($results as $details) <div class="col s2 l2"> {{ $details }} </div></div> My approach involves using the blade templating feature ...

Passing JSON information from a website to a Node.js server

<script type="text/javascript" src="data.json"></script> var mydata = JSON.parse(data); data = '[{"yer" : "Besiktas", "lat" : "41.044161", "lng" : "29.001056"},{"yer" : "Eminönü", "lat" : "41.017513", "lng" : "28.970939"},{"yer" : "Zeyt ...

Angular JS Changing Values in a Dynamic List

Creating Dynamic HTML with Angular Directives I'm working on code that generates HTML dynamically and includes Angular directives. Since these directives are late-bound, I need to ensure they execute and generate their respective template contents. I ...

Alter the class names on a div element every 3 seconds using React

Looking to animate the movement of CSS classes sequentially? Imagine starting with an image and after 3 seconds, shifting all classes downward so the last one appears on top, creating a dynamic carousel effect. Any assistance would be greatly appreciated! ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...