Getting Unordered Lists to Cooperate with Angular.js' Filters and Orders

Is it possible to sort based on price and rating using ng-click in an li element instead of a select menu? I have been searching for a solution and this is the closest I have found.

<ul class="restaurant-filter">
        <li> <i class="icon-search"></i>Organize results by "Price" &amp; "Rating"&hellip;
            <ul ng-model="priceAndRating">
                <li ng-click="price">Price</li>
                <li ng-click="rating">Rating</li>
            </ul>
        </li>
    </ul>

    <ul class="available-restaurants">
        <li ng-repeat="restaurant in availableRestaurants | orderBy:priceAndRating" ng-click="addRestaurantToEvent(restaurant.restaurantName)">
            <h6>{{restaurant.restaurantName}}</h6>
            <p>label one two three for five six</p>

            <i class="icon-chevron-right"></i>                    
        </li>
    </ul>

availableRestaurants is my object.

Answer №1

You didn't provide the structure of your data or controller, so I created a basic one that achieves the desired outcome. You can view the implementation on this fiddle.

Keep in mind that ng-click should trigger a function or execute code. To maintain separation of concerns, it's better to avoid mixing controller logic in the view. For instance, if the sorting criteria changes in the future, updating it in the view directly could lead to complications.

I included a sorting function that simply takes the property as input. Feel free to customize this according to your requirements.

HTML:

<div ng-app="miniapp">
    <div ng-controller="Ctrl1">
        <ul class="restaurant-filter">
        <li> <i class="icon-search"></i>Organize results by "Price" &amp; "Rating"&hellip;
            <ul>
                <li ng-repeat="option in sortOptions" ng-click="setSort (option)">{{option}}</li>
            </ul>
        </li>
    </ul>

    <ul class="available-restaurants">
        <li ng-repeat="r in availableRestaurants | orderBy:sort">
            <span>{{r.name}} - {{r.rating}}</span>                  
        </li>
    </ul>
    </div>
</div>​

JS:

function Ctrl1($scope) {
    $scope.sortOptions = ["Price", "Rating"];
    $scope.sort = "Price";
    $scope.setSort = function(type) { $scope.sort = type.toLowerCase(); };
    $scope.availableRestaurants = [{name: "Chevy's", rating: 6, price: 6},
                                  {name: "Burger King", rating: 2, price: 1},
                                  {name: "Red Robin", rating: 4, price: 4},
                                  {name: "Carl's Jr", rating: 5, price: 2}];
}

Answer №2

I have taken the liberty of transferring your code to a fiddle:

http://jsfiddle.net/blesh/tSHUf/

When using ng-click, it is important that it triggers an action, as opposed to what Tyrsius claimed, although it does not necessarily have to call a function. In my fiddle example, I am assigning a value to a scope property called order = 'price' or 'rating' based on the user's click.

Then you use orderBy:order, which will evaluate whatever is stored in $scope.order after the click event.

I trust this explanation clarifies any confusion.

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

I am encountering a horizontal scroll bar despite setting the width to 100%

I am just starting out as a beginner in web development. I decided to create a webpage to practice my HTML and CSS skills. However, when I set the width of all elements to 100%, I noticed that I am getting a horizontal scroll bar. I have tried troubleshoot ...

Saving dynamic object expressions that are constantly re-evaluated within Angular

Hello Everyone During the development of a prototype e-commerce website, I encountered an unexpected issue today. Specifically, the challenge lies in a method designed to take user input and apply discounts based on two criteria: 1). Validation of a cor ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

Obtain the templateUrl using the ui-router functionality

Perhaps the title is a bit unclear. I am currently working on two Angular apps nested within each other. Each has its own router created using `ui-router`. If I call a state that is not recognized by the main router, I would like it to search for this sta ...

Receiving empty response after attempting a cross-domain POST query with Cross-Origin Resource Sharing

When trying to send data cross domain via a POST request, I am facing an issue where jQuery's success handler is not being called. The technologies being used include Django, Apache, and jQuery. Here is the AJAX request setup that is causing the pro ...

When an ajax request fails with error 500, the Jquery script will come to a halt

I currently have a script that sends ajax requests at regular intervals and it is intended to keep working indefinitely. <script type="text/javascript"> var delay = 750; window.setInterval(endlessJob, delay); function endlessJob() { ...

Retrieve the text and image simultaneously using jQuery

I need to retrieve either text or image within a modal. Use textCont to retrieve text. The content within a div can be either text or image. It will retrieve whatever is present there. Below is the JavaScript code for text retrieval. var contId = 0; var ...

My Experience Dealing with an Issue on the Star Wars App

Hey there, good morning! I'm currently working on a project involving React. The data I am trying to retrieve is located at this link: . My aim is to display the movie data on my MovieDetail page. So far, I have successfully displayed string charact ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

Is it universally compatible to incorporate custom attributes through jquery metadata plugin in all web browsers?

Picture this: a fictional markup that showcases a collection of books with unique attributes, utilizing the metadata plugin from here. <div> Haruki Murakami </div> <div> <ul> <li><span id="book5" data="{year: 2011} ...

Numerous navigable tabs all on a single page

After following a tutorial on YouTube to create scrollable tabs, I successfully implemented it using Bootstrap 5. However, I'm facing challenges in getting multiple scrollable tabs to function on a single page. Although the tabs and tab-content are fu ...

Transforming a function into an array in TypeScript

I attempted to use the map() function on a dataURL array obtained from the usePersonList() hook, but I am struggling to convert my function to an array in order to avoid errors when clicking a button. import Axios from "axios"; import React, { us ...

The AngularJS call is successfully working in POSTMAN, however, it is encountering difficulties when executed in the AngularJS Application. The issue seems to be related to the response to

I am in need of CORS implementation in AngularJS. I am not utilizing CORS for my web API as I am using APIs from external sources. My aim is to retrieve data with basic authentication through AngularJS. Despite successful testing on POSTMAN, I am encounter ...

There was a TypeError encountered while trying to read properties of undefined in Next.js version 13

I've encountered a problem in the title with my post API endpoint that I created in Next.js. The purpose of my endpoint is for form submission, where I gather inputs and send them to my email. Currently, my code successfully sends the email and I rec ...

Output a variable that is generated from invoking an asynchronous function

I'm currently in the process of developing an application that is going to leverage the capabilities of a SOAP server through the use of the https://github.com/vpulim/node-soap module. One of the main challenges I am facing is how to efficiently crea ...

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

Eliminating unnecessary gaps caused by CSS float properties

I need help figuring out how to eliminate the extra space above 'Smart Filter' in the div id='container_sidebar'. You can view an example of this issue on fiddle http://jsfiddle.net/XHPtc/ It seems that if I remove the float: right pro ...

Merge the date and time values to create a unified datetime

I'm working with a date and time control and I need to combine the values. var startDate = jQuery('#startDatepicker').find("input").val(); var startTime = jQuery('#startTimepicker').find("input").val(); Another variable in my cod ...

After modifying the variable from 'let' to 'const' and replacing 'i++' with 'i+1' in

After some time of coding without tslint, I decided to enable it again. Upon doing so, I noticed some errors and promptly fixed them. I made the following change: for (const index = 0; index < combinedUniqueIndexes.length; index + 1) However, after m ...

The issue of Meteor and React Router resulting in blank rendering

I've been diligently following the steps outlined in the Meteor React Routing guide. However, after implementing the routing, my app mysteriously stopped rendering anything (despite working perfectly fine prior to adding routing), and I can't see ...