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

Dynamically assign properties to elements in VueJS

Is there a way to dynamically set the required property of an input element to true when rendering a list of elements, based on whether the list item has a specific setting? <input name="input" type="{{input.type}}" class="form-control" v-model="datase ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attemp ...

The debate between importing images and including them inline in NextJS is a hot

When using NextJS, what sets apart importing an image from directly including it with next/image? import logo from './logo.png'; <Image src={logo} /> /* versus */ <Image src={'/logo.png'} /> (This is pseudocode meant for ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

Coming back from retrieving data from an API

I'm having trouble with a function that performs a POST request to retrieve access tokens from an API. Although the function successfully prints the token to the console, I haven't been able to figure out how to properly parse and save the access ...

Getting data from an API with authorization in Next.js using axios - a step-by-step guide

click here to view the image user = Cookies.get("user") I'm having trouble accessing this pathway. I stored user data, including the token, using cookies. Please assist me with this issue. ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...

Implementing a Javascript solution to eliminate the # from a URL for seamless operation without #

I am currently using the pagepiling jQuery plugin for sliding pages with anchors and it is functioning perfectly. However, I would like to have it run without displaying the '#' in the URL when clicking on a link like this: www.mysite.com/#aboutm ...

The functionality of the bootstrap Dropdown multiple select feature is experiencing issues with the Onchange

Creating a Bootstrap Multiple Select Drop Down with dynamically retrieved options from a Database: <select size="3" name="p" id="p" class="dis_tab" multiple> <?php echo "<option>". $row['abc'] ."</option>"; //Fetching option ...

Embed an external website within a div element

Is there a way to embed an entire external website onto another site, without scroll bars or borders? I attempted this method but the entire page did not load, and there were still scroll bars and borders present. <!DOCTYPE HTML> <html> <b ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Undefined property error

router.post('/:token',(req,res)=>{ let language= req.query.language let name= req.query.name let param =[] if(req.path.length == 5){ param.push({ language: language },{ name: name }) ddp.personConnected(param, function(err, response) { i ...

Configuring Vuex State

Currently, I have a prop that is being bound to a child component. My goal is to eliminate this binding and instead assign the value to a data property in a vuex global state. <VideoPip :asset="asset" v-show="pipEnabled === true" /&g ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

What steps can I take to make sure JSON keys containing only digits are treated as Strings instead of Numbers?

Within a JSON String, I have IDs as keys, represented as Strings of numbers, while the values are actual Numbers (Float). The problem arises when parsing this information to obtain an object in Safari 10.1.2... var jsonData = "{\"53352\":0.6, ...

Instead of scrolling through the entire window, focus on scrolling within a specific HTML element

I currently have the following elements: #elementA { position: absolute; width: 200%; height: 100%; background: linear-gradient(to right, rgba(100,0,0,0.3), rgba(0,0,250,0.3)); z-index: 250; } #containerofA { position: fixed; ...

Create a filter system using a MERN stack that incorporates regex, a search box,

In an effort to understand how the MERN stack operates as a cohesive unit, I have taken on a hands-on approach by following tutorials from bezcoder. These include guides on Node.js/Express/MongoDb (Github entire code) and Reactjs (Github entire code). Sam ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...