What is the process for transferring ng-model values to a table in Angular?

My goal is to populate a table with JSON data using ng-repeat by clicking a button. I need to input either a first name or last name in order to display the results in the table. Is this the correct JavaScript function for achieving this?

JavaScript Function:

$scope.clickButton = function(enteredValue) {

$scope.reset();
$scope.items = data;

angular.forEach($scope.items, function (item) {
    if(item.fname === enteredValue || item.lname === enteredValue ){
        $scope.results.push({
            first: item.fname,
            last: item.lname,
            address: item.address,
            phone: item.phone

        });

JSP:

<input id="fName" name="fName" type="text" data-ng-model="enteredValue.firstName" />

 <input id="lName" name="lName" type="text" data-ng-model="enteredValue.lastName" /> 

 <button class="btn btn-primary" data-ng-click='clickButton(enteredValue)'>Button</button>

For a live example, check out Plnkr.

Answer №1

Is this the solution you were seeking?

let app = angular.module('myApp', []);

angular.module('myApp').controller('myController', ['$scope', '$http',
  function($scope, $http) {
    let data = $scope.info = [{
        "fname": "Tim",
        "lname": "Hill",
        "address": "Road",
        "phone": "1234"

      },

      {
        "fname": "Sue",
        "lname": "Summers",
        "address": "Street",
        "phone": "4321"

      }
    ];

    $scope.results = [];
    $scope.clickButton = function(enteredValue) {
      $scope.items = data;

      angular.forEach($scope.items, function(item) {
        if (item.fname == enteredValue.firstName || item.lname == enteredValue.lastName) {
          $scope.results.push({
            first: item.fname,
            last: item.lname,
            address: item.address,
            phone: item.phone

          });
        }
      });
      $scope.reset();

    }

    $scope.reset = function() {
      $scope.enteredValue.lastName = '';
      $scope.enteredValue.firstName = '';

    };

  }
]);
<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>

  <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efff0f9ebf2ffecb0f4eddeafb0adb0e6">[email protected]</a>" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
  <script data-require="ng-table@*" data-semver="0.3.1" src="http://bazalt-cms.com/assets/ng-table/0.3.1/ng-table.js"></script>
  <link data-require="ng-table@*" data-semver="0.3.1" rel="stylesheet" href="http://bazalt-cms.com/assets/ng-table/0.3.1/ng-table.css" />
  <link data-require="bootstrap-css@*" data-semver="3.0.0" rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />


  <script src="script.js"></script>

  <style>
    ul {
      border: solid 1px #404040;
      margin: 5px;
    }
    [ng-click],
    [data-ng-click],
    [x-ng-click] {
      cursor: pointer;
    }
  </style>
</head>

<div ng-app="myApp" ng-controller="myController">

  <form name="personForm" ng-submit="clickButton(enteredValue)" novalidate>
    <table>
      <tr>
        <td>
          <label>First Name:</label>
        </td>
        <td>
          <input id="pName" name="pName" type="text" data-ng-model="enteredValue.firstName" />
        </td>
      </tr>

      <tr>
        <td>
          <label>Last Name:</label>
        </td>
        <td>
          <input id="pName" name="pName" type="text" data-ng-model="enteredValue.lastName" />
          <button class="btn btn-primary">Search</button>
        </td>
      </tr>
    </table>
  </form>
  <table>
    <tr data-ng-repeat="result in results">
      <td data-title="'First Name'">{{result.first}}</td>
      <td data-title="'Last Name'">{{result.last}}</td>
      <td data-title="'Address'">{{result.address}}</td>
      <td data-title="'Phone'">{{result.phone}}</td>
    </tr>
  </table>
</div>

</html>

Answer №2

I have implemented some minor adjustments.

After the forEach block, I have inserted a call to $scope.reset(). This ensures that the entered data remains accessible for processing without being reset to empty. Additionally, I have utilized a temporary array.

Below is the revised JavaScript code:

$scope.results = [];
 $scope.clickButton = function(enteredValue) {


    $scope.items = data; 
    var tempArray = [];

    angular.forEach($scope.items, function (item) {
        if(item.fname === enteredValue.firstName || item.lname === enteredValue.lastName ){
            tempArray.push({
                first: item.fname,
                last: item.lname,
                address: item.address,
                phone: item.phone

            });
        }
    });

    $scope.results = tempArray;

    $scope.reset();

}

    $scope.reset = function() {
        $scope.enteredValue.lastName = '';
        $scope.enteredValue.firstName = '';
        tempArray = [];

    };

You can view the updated version on Plunker.

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

Incorporating an external SVG link into a React application

While I may not be an SVG expert, I haven't encountered any issues with loading SVGs in my React app so far. I prefer using the svg tag over the image tag because sizing tends to present problems with the latter option when working with external links ...

Array of Objects Returned by Mongoose

Need help understanding an issue. I'm facing a problem where my API is returning the whole object as an array for one route, even though the schema is identical to another route that returns the object correctly. The only difference I can see is tha ...

What is the best way to create a button with a dynamic background animation in React?

Looking to design a button with an animated background, possibly in gif or video format. An example of what I have in mind is the DOWNLOAD button on this website's main page: Ideally, I am hoping for a solution using React. ...

Store information in Factory and retrieve it in the controller

I am encountering an issue with my code. Below is the factory code: .factory('shareDataService', function() { var sharedData = {}; sharedData.shareData = function(dateFrom, dateTo) { var from = dateFrom; var to = dateTo ...

Can you help me understand the meaning of the message: [$rootScope:infdig] 10 $digest() iterations reached. Stopping! Watchers activated in the last 5 iterations

While many solutions have been discussed regarding fixing this issue, my main concern is understanding how to interpret the extensive list of information that accompanies the error message. Despite working with Angular on a daily basis for over a year, I h ...

Implement a function to delete an item from an array within a React object by utilizing the UseState hook

I am facing a challenge in React as I attempt to remove an element from an array within an array of objects using the UseState hook. Despite my efforts, the interface does not re-render and the object remains in place. From what I understand, in order for ...

Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties. The following code helped me achi ...

What is the optimal method for storing extracted JSON data?

One question on my mind is how to effectively store JSON data. I have a JSON file that I parse using JSON Library and now I have the data from the file. However, I want to be able to store this data for future use. I'm seeking advice on the best way ...

Embed schema information into HTML tags using JavaScript

Is there a way to insert text, specifically schema data, into an HTML div tag using JavaScript? While I know how to modify existing values within a tag like class, href, and title, I am struggling to find a method to add something entirely new. Essentiall ...

What is the best way to send a file object to a user for download?

When working within a route: app.get('some-route', async (req, res) => { // ... } I am dealing with a file object called file, which has the following structure: https://i.stack.imgur.com/ByPYR.png My goal is to download this file. Cur ...

Ensuring the accuracy of a personalized directive within a form

I have a challenge with validating a form that contains a custom directive, especially in cases where the scope is an isolate scope. In a regular scope, it's easy to validate, but how do we handle validation in an isolate scope scenario? Here is an ex ...

Modifying pagination numbers with Reactjs: A step-by-step guide

I am currently working on Reactjs (nextjs) and I have successfully integrated the "Nextjs" framework. The pagination is working fine, but the buttons are displaying as "1,2,3,20" instead of "1,2...20" (showing all numbers without using "..."). How can I mo ...

What is the process of adding information to a JSON file?

I'm looking to store my data in an external JSON file and have it update the list when the page is reloaded. Can anyone assist with this? Below is my code: $scope.addUser = function() { var user = { id: null, login: '', ...

Scala: Best Practices for Parsing Multiple JSON Files in Subdirectories

I need assistance with finding a code snippet in Scala for reading multiple nested JSON files within subdirectories in Hadoop. It would be even more helpful if we could consolidate the data from these JSON files into one single file located in a different ...

What is the best way to create a Snap.svg map using AngularJS?

I am in the process of creating a web interface for an online board game. My goal is to load a Snap.svg map using Snap.load asynchronously. Once the map is loaded, I intend to attach a watch to a scope property and apply colors to the map based on that pr ...

Getting the error message "t is not a function. (In 't(i,c)', 't' is an instance of Object)" while attempting to switch from using createStore to configureStore with React Redux Toolkit

I am attempting to switch from react-redux to its alternative react-redux toolkit but I kept encountering this issue t is not a function. (In 't(i,c)', 't' is an instance of Object) and I am unsure of its meaning. Here is the c ...

Loop through the .getJSON response using jQuery

I've searched high and low for an answer to my question, but I can't seem to find one. My issue is with iterating over a JSON array (and its object) using jQuery's .each() method to print out all the values. Here is the JSON structure: { ...

Teaching Selenium how to input text into Google's login field (programming with Python)

Encountering an issue with sending keys to the username and password fields in Google's sign-in box using Selenium. Despite locating the web elements with the IDs "Email" and "Passwd", I'm unable to input any keys into them. Here is the code sni ...

Utilizing escape characters in Ionic 2 to import JSON data into a database

Currently, I am facing an issue while trying to bulk-import JSON-data using the cordova-sqlite-porter into a Database of an Ionic 2 App. The process works smoothly for the most part, however, I am having trouble escaping characters like ' and ". Here ...

How to dynamically update data in Angular without the need for a page refresh or loading?

Looking to enhance a wishlist feature by enabling users to delete items from the list without the need for a page refresh. Here's my approach: wish.controller('wishCtrl',['$scope','$http','$cookies','$wind ...