Here are the steps to pass the selected dropdown value to ng-repeat for ordering:

I have a dropdown box with options for filtering data in an ng-repeat by different criteria. How can I pass the selected value from the dropdown to the ng-repeat orderby?

Here is my dropdown:

<select name='filter_range' id='filter_range' onchange='filter()'>
    <option value='mrplow'> MRP Low To High</option>
    <option value='mrphigh'> MRP High To Low </option>
    <option value='qtyhigh'> Qty Low To High </option>
    <option value='qtylow'> Qty High To Low </option>
</select>

Using AngularJS:

<div ng-app="myApp" ng-controller="MyController"> 
    <div ng-repeat="grp_val in sample | orderBy:selectedValue">
        <label>{{grp_val.product}}</label><br>
    </div>
</div>

How can I dynamically set the orderBy value to the one selected in the dropdown?

Answer №1

Let me demonstrate an example that closely resembles your issue:

    const fruits = ['apple', 'banana', 'cherry'];
    console.log(fruits.sort()); // Output: ["apple", "banana", "cherry"]
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
<div id="app">
  <p>Original Array: {{fruits}}</p>
  <p>Sorted Array: {{sortedFruits}}</p>
</div>

<script>
new Vue({
  el: '#app',
  data: {
    fruits: ['apple', 'cherry', 'banana']
  },
  computed: {
    sortedFruits() {
      return this.fruits.sort();
    }
  }
});
</script>

You can find more information at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

I hope this sheds some light on your query.

Answer №2

If the data you are working with contains properties like "mrp" and "qty", this solution should help resolve your issue:

<select ng-model='orderProp' name='filter_range' id='filter_range'   onchange='filter()'>
    <option value='mrp'> MRP Low To High</option>
    <option value='-mrp'> MRP High To Low </option>
    <option value='qty'> Qty Low To High </option>
    <option value='-qty'> Qty High To Low </option>
</select>

<div ng-app="myApp" ng-controller="MyController"> 
    <div  ng-repeat = "grp_val in sample | orderBy: orderProp"
        <label>{{grp_val.product}}</label><br>
    </div>
</div>

Make sure to adjust the option values of your select box based on the properties of your "sample" object, then connect the select box value to "orderProp" which will be used in the ng-repeat directive with the orderBy filter.

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

Alerts being used by Jquery Validation Engine to showcase errors

In the validation engine, my goal is to have error messages appear in a JavaScript alert box instead of as small tooltips right next to the input fields. $("#main_form").bind("jqv.form.result", function(event, errorFound) { if(errorFound) aler ...

Updating the view manually is necessary when using AngularJS $routeProvider and resolve feature

I am facing issues with $routeProvider in updating the view automatically. Currently, I am working on converting a chapter 22 example from Adam Freeman's Pro Angular book, originally based on Deployd, to Express-Mongo. Strangely, the automatic refres ...

Tips on eliminating overlapping strokes

I'm having trouble with drawing an array of circles that are meant to intersect a series of lines. The issue I face is that if the circles overlap, a stroke appears underneath them which I want to remove. Does anyone have any suggestions on how to el ...

The drop-down menu keeps flickering instead of remaining open when clicked

I am facing an issue with a dropdown menu in my webpage. The menu is initially hidden, but should become visible when the list element containing it is clicked. I have written JavaScript code to add a class that changes the visibility property to visible u ...

What are the steps to integrating databases with HTML5?

I currently have SPA applications developed with angularjs, but I am in need of creating an installer that allows users to work offline using a secure local database. I experimented with IndexedDB and converted my SPA into a Chrome extension, however, I di ...

calling object functions using additional parentheses

After reviewing the passport.js documentation, I came across this piece of code: app.get('/login', function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) { return next(err); } if (!u ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

extract the field name from the json object

I need to send coordinates to the Google Maps API, but I'm struggling to remove the field name from my JSON object before sending the parameters. Object {TempPoints: "{lat: 51.478,lng: -3.192},{lat: 51.478,lng: -3.192…{lat: 51.47840998047034,lng: - ...

Laravel 5.0 facing issues with AJAX requests

For my Laravel 5.0 project, I am utilizing Google API's for Google Oauth login. After successfully retrieving the email and id_token of the currently logged-in user, I aim to send this data to the SigninController to access our own API. The goal is to ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

Securely Upload Files with JavaScript

Are there any methods to utilize javascript or ajax for encrypting file uploads securely? If so, could you provide a sample code snippet or direct me to a functional example? ...

Combining photos seamlessly and bringing them to life through animation upon window loading

My main goal is to seamlessly fit the images together, but I'm struggling to achieve this. I tried using masonry, but unfortunately it didn't work for me. All I want is to tightly pack the divs together. For instance, in my fiddle example, I woul ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

Secure an input field for exclusive attention. React

How can I lock the focus of my input field? I attempted using the following code: onBlur={this.click()} However, it was not successful. What is the correct way to accomplish this? ...

An angular component that is functioning properly when connected to a live server, however, it is experiencing issues when trying to run `

I tried integrating versitka into my Angular component by placing the version HTML file and all necessary assets in the appropriate directories. However, when I run ng serve, only the HTML file seems to be working, while the CSS and images fail to load. I ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

The ideal formats for tables and JavaScript: How to effectively retrieve arrays from a table?

Given the task of defining a function that extracts the mode of weights from an HTML table containing age and weight data for individuals within a specified age range. The function needs to be able to handle tables of any size. I am looking for the most ef ...

Combine all the HTML, JavaScript, and CSS files into a single index.html file

So here's the situation - I am utilizing a C# console application to convert four XML files into an HTML document. This particular document will be circulated among a specific group of individuals and is not intended to be hosted or used as a web app; ...

Ensuring security against cross site scripting attacks on window.location.href

Currently, I'm utilizing window.location.href to redirect the page to an external URL: <Route exact path={rootUrl} component={() => { window.location.href =`https://${window.location.hostname}/www/testurl?google=true`; return null; }} /> How ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...