Updating DOM elements in AngularJS based on search results and user clicks

I have a query regarding my angular web app, which includes an ajax call for json-formatted dates to display them in a table. The app features a search input, two sorting buttons (for age or name), and a profile sidebar element.

I have successfully updated the sidebar info (name, age, pic, phrase, fav animal) when clicking on table rows. However, I need to update the sidebar information in the same way when pressing the sorting buttons (sorting by name or age), as well as when making search inputs. I am looking for a way to populate the sidebar with JSON data based on the clicked sort buttons or search inputs. Thank you in advance!

Here is the HTML snippet

<div class="app container-fluid"  ng-controller="mainController">
    <form>
      <div class="form-group">
        <div class="input-group">
          <div class="input-group-addon"><i class="fa fa-search"></i></div>
          <input type="text" class="form-control" placeholder="Search right person" ng-model="searchAnimal" ng-model="updateAnimal">
        </div>      
      </div>
    </form>
    <div class="row">
      <div class="col-sm-12">
        <div class="toolbar">
          <button ng-click="sortType = 'name'; sortReverse = !sortReverse; clickAnimal()" class="btn btn-default"><i class="icon fa fa-sort-alpha-asc"></i><span> Sort by name</span>
            <span ng-show="sortType == 'name' && !sortReverse"></span>
          </button>
          <button ng-click="sortType = 'age'; sortReverse = !sortReverse; clickAnimal()" class="btn btn-default"><i class="icon fa fa-sort-numeric-desc"></i><span> Sort by age</span>
            <span ng-show="sortType == 'age' && !sortReverse"></span>
          </button>
        </div>
      </div>
    </div>
    <div class="row" ng-cloak>
      <div class="col-sm-4 col-md-3 col-lg-2">
        <div class="thumbnail"><img ng-src="{{ animImage }}.svg"/>
          <div class="thumbnail-caption"><h3>{{ animName }}</h3><table class="user-info table table-responsive" ><tbody><tr><td>Age:</td><td>{{ animAge }}</td></tr><tr><td>Favorite animal:</td><td>{{ animImage }}</td></tr><tr><td>Phone:</td><td><span>{{ countryCode }} </span>{{ animPhone }}</td></tr></tbody></table><p><b >Favorite phrase:</b><span> </span><span>{{ animPhrase }}</span></p></div>
        </div>
      </div>
      <div class="col-sm-8 col-md-9 col-lg-10">
        <table class=" user-list table table-striped">
        <thead>
          <tr>
            <td>
              <a href="#">
                Image 
              </a>
            </td>
            <td>
              <a href="#">
              Name 
              </a>
            </td>
            <td>
              <a href="#">
              Age 
              </a>
            </td>
            <td>
              <a href="#">
              Phone
              </a>
            </td>
          </tr>
        </thead>
        <tbody>
          <tr ng-cloak ng-click="showAnimal()" ng-repeat="animal in userList | orderBy:sortType:sortReverse |filter:searchAnimal">
            <td><img ng-src="{{ animal.image }}.svg" class="user-image"></td>
            <td>{{ animal.name }}</td>
            <td>{{ animal.age }}</td>
            <td>{{ animal.phone }}</td>
          </tr>
        </tbody>
      </table> 
      </div>
    </div>  
  </div>

And here is the Angular part: angular.module('displayApp', []).controller('mainController', function($scope, $http) { $scope.sortType = 'name'; // set the default sort type $scope.sortReverse = false; // set the default sort order $scope.searchAnimal = ''; // set the default search/filter term $http.get("data.json") .then(function(response) { $scope.userList = response.data; $scope.animName = $scope.userList[0].name; $scope.animImage = $scope.userList[0].image; $scope.animAge = $scope.userList[0].age; $scope.animPhone = $scope.userList[0].phone; $scope.animPhrase = $scope.userList[0].phrase; }); $scope.countryCode = "8"; $scope.showAnimal = function(){ $scope.animName = this.animal.name; $scope.animImage = this.animal.image; $scope.animAge = this.animal.age; $scope.animPhone = this.animal.phone; $scope.animPhrase = this.animal.phrase; } });

Answer №1

Make sure to modify the clickAnimal() function so that it can update the information in the $scope.showAnimal function whenever you select a sorting button. This involves assigning the animal data to the first entry in the table when a sort button is activated.

To learn more about altering $scope values, refer to this link:

Check out this demonstration of how $scope.apply is utilized: http://jsfiddle.net/k19966h8/

Here's a brief example:

function Ctrl($scope) {
  $scope.message = "Waiting 2000ms for update";

    setTimeout(function () {
        $scope.$apply(function () {
            $scope.message = "Timeout called!";
        });
    }, 2000);
}

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

Error message: When using the Semantic UI React Modal, the Portal.render() function requires a valid React element to be returned, otherwise

Currently, I am working on integrating the Semantic UI React modal into my dashboard application built using React. To facilitate this integration, I have developed a ModalManager component that will be utilized in conjunction with Redux to handle the stat ...

Events for focusing and blurring top level windows

I'm encountering an issue with a basic frameset setup <frameset rows="100, 200"> <FRAME name="listener" src="frame1.html"> <FRAME name="content" src="http://www.someexternalurl.com/"> </frameset> Within the listener ...

URL validation RegEx in AngularJs using Javascript

I am looking for the following URLs to return as true other.some.url some.url some.url/page/1 The following URL should be flagged as false somerandomvalue Here is the regex I have been experimenting with so far: /^(?:http(s)?:\/\/) ...

A guide on performing CRUD operations on locally stored JSON data using React JS

Retrieve the JSON data from any endpoint and store it locally fetch("any endpoint") .then((response) => response.json()) .then((responseJson) => { this.state ={ data:responseJson } }) How to perform CRUD operations on a sample JSO ...

Tips for updating a plugin from phonegap 2.5 to the most recent version 3.1, and the steps to follow when including a new plugin in phonegap

$('#sendSms').click(function(e){ alert("Sending SMS in progress");//After this alert, I encountered continuous errors and couldn't determine the root cause var smsInboxPlugin = cordova.require('cordova/plugin/smsinboxplugin'); ...

Is there a way to generate a fresh array by filtering an array of objects based on a single value?

I am currently working with an array of objects: const dummyLinkRows = [ { id: 'entity:link/1:en', categories: [ { name: 'Human Resources' }, { name: 'Social' } ], nam ...

Having issues with v-for in Vuejs? It seems to be looping multiple times

<div v-for="item in items" :key="item.id"> <div v-for="accordion in accordions" :key="accordion.title" class="line" :class="{ green: accordion.text === 'AllaboutVue', red: accordi ...

Vue-resource is returning a Promise object

How do I access the response data in an Ajax call? When I log response.text(), it displays a PromiseObj. Console PromiseObj context: undefined promise: Promise {status: "resolved", result: ")]}',↵{\"Result\":\"SUCCESS\",&bs ...

Having trouble with the tooltip feature in Bootstrap?

I've searched high and low, including on this site! I've experimented with all sorts of code, but nothing seems to make the tooltips function in BootStrap. It's beginning to really frustrate me!! Does anyone happen to have the working js co ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Breaking Down and Optimizing your Code with Destructuring and

Currently, I am performing some basic destructuring in Javascript: //@flow "use strict"; (function(){ const {a,c} = check(true); })(); function check(bool:boolean):{|a:string,c:string|}|{||}{ if(bool){ return { a:"b", c:"d" } ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Merge JSON objects while retaining duplicate keys

I am looking to merge two arrays containing JSON objects while retaining duplicate keys by adding a prefix to the keys. In this specific scenario, the data from 'json2' is replacing the data from 'json1' due to having identical keys, bu ...

Update the image source through an AJAX call

I've experimented with various methods to update an image src using an AJAX request. The new URL is obtained through the AJAX call, and when inspecting the data in Developer Tools, the 'DATA' variable contains the correct URL. However, the i ...

Creating a mapping in Node.js to write to a serial port and then retrieve the

Currently, I am utilizing the node-serialport module for serial port communication. My goal is to send the command ATEC and receive a response of ECHO. However, the process of sending and receiving data is asynchronous (after sending the data, the timing ...

Issues with APIs surfaced following the transition from DataGridPro to DataGridPremium

In my current project, we initially implemented the MUI X DataGrid but later switched to DataGridPro due to business requirements. Recently, we upgraded our plan from Pro to Premium which has caused some unexpected issues in our existing code. I am using " ...

Limiting the input in a text box to only allow whole numbers and no decimal values

What is the best way to limit a textbox to only accept whole numbers and exclude decimal values and alphabets? ...

After running the command "npx/npm create-react-app hello" to create a react app, I received the following message

Whenever I try to execute this command for creating a React app: C:\WINDOWS\system32> npm i create-react-app -g hello I receive the following message in my cmd prompt: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf ...

Switch language by entering a specific URL (VueJs)

I have successfully integrated localisation using vue-i18n. In my main.js file: import Vue from 'vue' import { i18n } from './plugins/i18n' import Cookie from "vue-cookie"; if (!Cookie.get('locale')) { Cookie.set(' ...

Load Angular scripts only when needed

I need to develop an application that can dynamically register new Angular Controllers obtained from a script. This application should load the minimum necessary scripts at startup and then fetch additional scripts as needed from other modules. Here' ...