Update the ng-repeat attribute in HTML using either vanilla JavaScript or AngularJS

When the user clicks on the 'sort by book title' button, I want to change the ng-repeat="x in books' to ng-repeat="x in books|orderBy:'country'" in the HTML code.

How can I achieve this action using JavaScript/Angular?

Here is a link to the code

<section id="App2" ng-app="form-input" ng-controller="ctrl">
  <summary class="row book-component">
     <div ng-repeat='x in books' class="col-md-12 col-sm-12 col-xs-12">
       <img class="thumbnail-image"> 
         <div> 
            <h2 ng-bind="x.title" class="title"></h2>
            <h4 ng-bind="x.author" class="author" style="color:grey"></h4>
            <hr>
            <h5>FREE SAMPLE <span class="review" onclick="review(this)">REVIEW</span></h5>
         </div> 
     </div>
  </summary> 
  <button style="margin-top:30px" class="btn-lg btn-success" 
  ng-click="sort()" onclick="sort()">Sort by book title</button>
</section>
<script>
  var app2 = angular.module('form-input', []);
    app2.controller('ctrl', function($scope) { 
    $scope.books=[
      {title:'Jani',author:'Norway'},
      {title:'Hege',author:'Sweden'}
    ];       
  })
</script>

Answer №1

Set the order filter as a variable, then update that variable using ng-click to invoke a controller function that takes the field as an argument:

<section id="App2" ng-app="form-input" ng-controller="ctrl">
  <summary class="row book-component">
     <div  ng-repeat='x in books | orderBy: order' class="col-md-12 col-sm-12 col-xs-12" >
       <img class="thumbnail-image" > 
         <div> 
            <h2 ng-bind="x.title" class="title"></h2>
            <h4 ng-bind="x.author" class="author" style="color:grey;"></h4>
            <hr>
            <h5>FREE SAMPLE <span class="review" onclick="review(this)">REVIEW</span></h5>
         </div> 
     </div>
 </summary> 
 <button style="margin-top:30px" class="btn-lg btn-success" ng-click="changeOrder('title')">Sort by book title</button>
</section>

Javascript:

  var app2 = angular.module('form-input', []);
  app2.controller('ctrl', function($scope) { 
    $scope.order = 'author';
    $scope.books=[
      {title:'Jani',author:'Norway'},
      {title:'Hege',author:'Sweden'}
    ];       
    $scope.changeOrder = function (order) {
        $scope.order = order;
    };
  });

https://jsfiddle.net/dbxtcw9w/1/

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

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

The if-else statement doesn't seem to be functioning correctly once the else condition is included

I'm currently developing a search function for an address book that iterates through the contact array and displays them in a popup. Initially, it was working correctly by finding and displaying the contacts that were found. However, once I added the ...

Adjusting the tab order dynamically within a navigation menu

I am currently facing an issue where the focus is not being ignored when the drawer is closed. Even with the showDrawer reference set to false, I can still tab through links in the closed drawer. Setting tabindex="-1" on the <nav> element does not pr ...

Is sending cookies the sole method to convey a directive from a server to a client for the execution of JavaScript code?

Simply put: How can a server send a message to a client to run JavaScript code on a page? It's not an Ajax request, but a basic GET browser-server request. Imagine this code in my app's front-end JavaScript file: if( condition_1 ) { FB.get ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

The issue persists as the Ajax request continues to return false

I have created a verification program using an ajax request: $("#codeSbmt").click(function(){ var $input = $("#fourDigit"); codeCheck("codeTest.php?q=" + $input); }) function codeCheck(url) { var xh ...

Ways to target only the adjacent div

My goal is to target only the next div with the class name indented. Each indented div should have the same id as the <li> element right before it. Currently, I want each div with the class name indented to have the id of the previous <li>. He ...

Deactivate the button while you wait for the Google Maps directionService

When utilizing the Google Maps service to plot a route with multiple waypoints and under slow 3G conditions, I need to deactivate an HTML button until the new route is traced. calculateRoad(departure: any, arrival: any) { const request = { origin: ...

Is there a distinction in functionality when utilizing fat arrow syntax versus traditional syntax for ES6 class methods and React?

Consider these two examples showcasing different ways to write an ES6 class method: The first example uses the non-fat arrow, or concise method syntax: class Test extends Component { handleClick() { return 'clicked' } } The second exam ...

Ways to avoid extra function loads in JavaScript

I'm currently working on an instant search feature and have some code implemented: $(function() { var timer; $("#searchterm").on('keypress',function() { timer && clearTimeout(timer); timer = setTimeout(doStuff, 800); tim ...

Angular: failure to update a specific portion of the view

I'm currently working on a directive template that features the following code snippet: <div class="colorpicker"> <div>Chosen color</div> <div class="color_swatch" style="background-color: {{ngModel}}">&nbsp;</div> & ...

The following working day with Moment.js

I'm having an issue trying to retrieve the next business day with my code. Currently, it is only displaying the day immediately following. Despite looking into similar questions for a solution, I have yet to identify the error. While this question is ...

Analyzing the original data form versus the modified data

I'm dealing with a form in React that utilizes react-hook-form and the useFieldArray method for adding dynamic steps. The challenge I'm facing is how to compare the original data passed to the form with the edited data, in order to make correspon ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

AngularJS tips for resolving an issue when trying to add duplicates of a string to an array

Currently dealing with a bug that occurs when attempting to push the same string into an array that has already been added. The app becomes stuck and prevents the addition of another string. How can I prevent the repeat from causing the app to get stuck w ...

Access scope information when clicking with ng-click

I am currently using a php api to update my database, but I want the ability to choose which item gets updated with ng-click. app.controller('ReviewProductsController', function ($scope, $http) { $scope.hide_product = function () { ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

Create an array populated with unclosed HTML tags that need to be rendered

I'm trying to display a simple list, but it seems like React is having trouble rendering unclosed HTML elements that are pushed onto the list. This results in an error: ReferenceError: el is not defined If I use single quotes (') bookingStat ...

Error: Attempting to access properties of an undefined object (specifically 'query')

My productController.js const Product = require('../models/product'); const ErrorHandler = require('../utils/errorHandler'); const catchAsyncError = require('../middlewares/catchAsyncErrors'); const APIFeatures = require(&apo ...

Vue3 - Implementing a seamless communication channel between two child components

Vue 3 has brought about changes in my component structure, as shown below: https://i.sstatic.net/bgtPB.png In this setup, ChildA can communicate with ChildB and requires ChildB to update its state accordingly. In Vue 2, I could send an event from ChildA: ...