Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this:

<select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod">
  <option ng-repeat="sortMethod in sortMethods">{{sortMethod}}</option>
</select>

The available sort methods are defined as follows:

$scope.sortMethods = ['created', 'likes.count'];

I am utilizing the sortMethod variable to order a collection of objects:

<li ng-repeat="story in feedData|orderBy:sortMethod">
  Panel Count: {{story.frameURIs.length}}
</li>

Everything seems to be working correctly, however, the problem lies in the aesthetics of the select box options. Currently, it displays "created" and 'likes.count", but I would prefer it to show something more user-friendly like "Most Recent" and "Most Popular".

I attempted to modify sortMethod by using an array of objects:

$scope.sortMethods = [{'displayVal': 'Most Recent', 'sortVal': 'created'}, {'displayVal': 'Most Popular', 'sortVal': 'likes.count'}];

I then tried displaying sortMethod.displayVal in the select element, and sorting by

<li ng-repeat="story in feedData|orderBy:sortMethod.sortVal"
, but unfortunately, this seemed to result in an erratic ordering. Is there a way to create visually appealing select options without altering the feedData information? It's worth noting that feedData is provided by a third party and cannot be modified.

Answer №1

Great job on focusing on creating the appropriate View Model for sortMethods.

Make sure to utilize ng-options to generate options for your select input. This will allow you to define display values and specify the selected object.

In your situation, consider selecting the complete sortMethod object (assigned to ngModel) while displaying the label of sortMethod.displayVal. Then, use the sortVal for filtering purposes.

Here's how it can be structured:

<select ng-model="selectedSortMethod"
   ng-options="sortMethod as sortMethod.displayVal for sortMethod in sortMethods">
</select>

<li ng-repeat="story in feedData | orderBy:selectedSortMethod.sortVal">
  Panel Count: {{story.frameURIs.length}}
</li>

Next, in the controller section:

// Follow a similar approach as shown below:
$scope.sortMethods = [
   {displayVal: 'Most Recent', sortVal: 'created'},
   {displayVal: 'Most Popular', sortVal: 'likes.count'}
];

$scope.selectedSortMethod = $scope.sortMethods[0];

Check out this Plunker demo for reference.

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

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

No specification has been provided for the delivery

I'm currently working with the Meteor framework and I am attempting to send an uploaded file (HTML input) from the client to the server using the npm package Delivery. Below is my code: Client side : var socket = io.connect('http://0.0.0.0 ...

Sorting a JSONArray of JSONObjects that contain nested JSONObjects - here's how!

Sorting a JSONArray of JSONObject is something I can do, but I encountered an issue when trying to sort an array structured like this: [{ "key1": "value1", "key2": "value2", "key3": { "key4": "value4", "key5": "value5" } }, ...

Testing an AngularJS controller that relies on route resolution is an integral part of the development

I am having difficulty writing unit tests for my controller because it relies on data that is fetched when the route is resolved. I need to find a way to test this without encountering errors related to missing "locals". The controller code snippet: myMa ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Validate form for radio group

Hello Experts, I am currently working on developing a form that includes a JavaScript validation function for a radio group. The main objective is to have a division pop up when either "Monday" or "Tuesday" is checked, and no popup when "None" is selected ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

JavaScript: Discovering the art of "utilizing RESTful APIs"

After several years of coding in JS, I am now expanding my knowledge. I have noticed many job postings asking for familiarity with REST APIs and experience consuming RESTful services. I have a solid grasp on AJAX basics using both vanilla JS and jQuery. I ...

JQuery is having trouble with playing multiple sound files or causing delays with events

I've been working on a project that involves playing sounds for each letter in a list of text. However, I'm encountering an issue where only the last sound file is played instead of looping through every element. I've attempted to delay the ...

What is the formula for determining the REAL innerWidth and innerHeight?

I am currently working on a responsive website using Bootstrap and I am looking to create an element that perfectly fits the screen size. When I set the height/width to 100%, the browser includes the toolbar, other tabs, and the Windows taskbar in the cal ...

Tips for concealing dynamically generated div elements within a VueJS v-for loop

Is there a way to hide dynamically generated div elements in VueJS? In my chatbot application, messages are passed through a prop called messages. These message arrays create multiple Divs on the screen displaying information. One particular Div is used to ...

The getElementByID function functions properly in Firefox but does encounter issues in Internet Explorer and Chrome

function switchVideo() { let selectedIndex = document.myvid1.vid_select.selectedIndex; let videoSelect = document.myvid1.vid_select.options[selectedIndex].value; document.getElementById("video").src = videoSelect; } <form name="myvid1"> <s ...

Using Gmail in conjunction with Heroku for email delivery

After completing an order in my web app, I want to automatically send a confirmation email. I decided to use Nodemailer as it is a popular npm package for this purpose. I successfully coded the functionality and tested it in my local environment. Howeve ...

Tips for emphasizing specific sections of text in CodeMirror utilizing substring positions

I am currently utilizing CodeMirror () as a text editor with additional functionalities. One of these features includes highlighting specific words or groups of words based on their positions within the original string. I have an external structure that st ...

Error message received when calling a function within a Vue watcher states "function is not defined"

My goal is to trigger a function in a Vue component when a prop changes using a watcher: props: [ 'mediaUrl' ], watch: { mediaUrl: function() { this.attemptToLoadImage(); } }, medthods: { attemptToLoadImage: function() { console ...

Unable to set the active tab using $rootScope

Is there anyone who can assist me with the issue I am currently facing? I have a NavCtrl to manage my active tags, and although I was able to change the active tab when clicking on the menu item, it does not update when clicking on links in the body views. ...

Tips for positioning the overlay to match the icon list when hovering- JavaScript/Cascading Style Sheets (CSS)

My challenge involves a list of <li>'s accompanied by an icon that, when hovered over, displays an overlay containing information about the 'test'. The setup looks something like this: test1 test2 test3 and so forth.... Here' ...

CSS hover effect ceases to function after the button has been clicked once

I am facing a dilemma with styling that I can't seem to resolve. There is a basic toggle feature on my page with two options -- the user can select either Toggle1 or Toggle2, resulting in different data being displayed dynamically based on the active ...

How to Send Data to ASP.NET MVC Controller Using AJAX Request with jQuery

I am trying to send parameters to a controller from jQuery, but I am struggling with it. The call works fine without parameters when the URL is just /SurveySection/EditLocalization. Shouldn't it be something like this: /SurveySection/EditLocalization? ...