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

I am encountering an issue where my like button is returning a Json object { liked: true } but it is not functioning correctly with my ajax call in my Django application whenever a user tries to click the

Having trouble creating a like button with an AJAX function in Django. Every time I click on the button, it redirects me to a different page showing a JSON object that returns {liked: true}. Why is this happening? It's been quite challenging for me to ...

Issues encountered while modifying Vue data

In my Vue JS 2 code, I have structured my data as follows: data : { newBus: { name: '', hours: { sunday: '', } } } When setting the data usi ...

Enhancing JavaScript Arrays by incorporating data from a JSON file

Could you kindly advise me on what I might be doing incorrectly here? It seems like a simple issue, but it has taken up the entire day. All I wanted to do was add a value to an array called messages from a JSON file. function get_message(params) { va ...

Angular protection filter

Every time I used Angular CLI to generate a new component, it would create the component with standard parameters: @Component({ selector: 'app-test1', templateUrl: './test1.component.html', styleUrls: ['./test1.component.css ...

Restrict the number of rows displayed in the ui-grid to the maximum

I'm looking to adjust the height of the ui-grid so that it fits the size of 3 rows. After reviewing the ui-grid documentation, I noticed that there is a minRowsToShow property available, but couldn't find an equivalent for maxRowsToShow. I' ...

What could be causing the mysql-event to not function properly in a Node.js environment?

const MySQLEvents = require('mysql-events'); const databaseInfo = { host: 'localhost', user: 'root', password: '' //blank password }; const mysqlEventWatcher = MySQLEvents(databaseInfo); console.log(mys ...

The access-control-allow-headers token is absent from the CORS header 'Access-Control-Allow-Headers' during the CORS preflight process

I am facing an issue with two VS projects: one has MVC5 controllers exposed, while the other is an Angular client. I need the Angular client to be able to query the controllers. I have done some research and attempted the following steps: I added the f ...

Differentiate among comparable values through placement regex

I'm currently tackling a challenge involving regex as I work on breaking down shorthand CSS code for the font property. Here is my progress thus far: var style = decl.val.match(/\s*(?:\s*(normal|italic|oblique)){1}/i); style = style ? style ...

Utilizing an object map to pass objects as props without losing their keys

I have an array of objects named obj, structured as follows: { "root": [ { "key": "mihome", "label": "home", "action": "url", ...

The element is anchored within a div, but its position is dependent on a JavaScript script

I am dealing with a situation where I have a div named "Main_Card" containing text and an icon. When the icon is clicked, it moves the "Main_Card" along with everything inside of it. The challenge arises when I need to set the icon's position as eithe ...

Mastering Protractor for AngularJS testing - Effectively chaining promises for seamless animationswaitForAnimationCompletion

I'm in the process of creating an automated test suite for our company's AngularJS application. I've already developed several test cases that are running smoothly, but I've hit a roadblock with the current test I'm working on invo ...

How can you effectively blend Vue/Angular with other JavaScript resources to enhance your development process?

My curiosity lies in understanding how front-end javascript libraries such as Vue and Angular can seamlessly integrate with other libraries and assets. For instance, if I were to procure a website template already equipped with additional javascript, is it ...

Even after applying trim() function, PHP's return statement still adds spaces unnecessarily

My function is supposed to return a boolean, but for some reason, it is adding spaces at the beginning of the string. Even after using trim(), the spaces persist. What could be causing this unexpected behavior? PHP function checkFile($v){ $result = is_ ...

A Guide on Adding Excel-Like Filtering Functionality to AngularJS

I am struggling to implement a simple Excel-like filter for a table using AngularJS (v.1). I have shared my code snippet below and would appreciate any help to show filtered data in the table after checking a checkbox and clicking on the OK button. I have ...

Erase jQuery from the text

I am struggling with splitting or removing text from a filename. For example, if I have filenames like: 200726100_50-0002.JPG 230514008_60-0001.JPG The desired result should be: 230514008_60.JPG 200726100_50.JPG Am I not using the split function cor ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

When moving the cursor quickly, a vertical line does not appear upon hover

I am facing an issue with the vue-chartJs library. When I move the cursor fast, the vertical line on hover does not show up. However, when I move the cursor slowly, it works perfectly. Can anyone offer assistance in solving this problem? onHover: functi ...

Create a function that triggers when a user clicks, opening a new tab with a specified

I am currently facing a challenge in my project where I need to make all links within a modal open in a new tab. Unfortunately, due to the limitations of using angular, manipulating the DOM is proving to be more difficult than anticipated. Is there a solut ...

Merge web address when form is sent

I'm currently working on a search application using the Django framework and the Yelp API as my backend, which is functioning properly. However, I am facing some challenges with the frontend development, specifically integrating Leaflet.js. My search ...

Error: Variable 'err' is undefined in Node.js

Why am I getting a ReferenceError: err is not defined even though it is supposed to be defined here? const sampleObject = require('./sampleObject'); const sampleModel = (callback) => { if (true) { sampleObject.sampleRetrieval(err ...