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

Updating a single document in Node JS using Express is a simple and straightforward process

I'm having trouble understanding why my documents aren't updating. When I retrieve any record and load it into the form using http://localhost:3000/update2?buyerID=2299, the field doesn't update when I make changes and click submit. It rema ...

How can CSS and JavaScript be used to strategically position two upright images next to each other within a dynamically resizing container?

Looking for a way to display two portrait images side by side within a flexible container with 100% width? The challenge I'm facing is accommodating varying widths of the images while ensuring they are the same height. <div class="container"> ...

Is there a way to animate without specifying a duration?

Exploring the capabilities of the Animated component in react-native, I came across the powerful Animated.timing(); function which operates within a specific duration defined as duration: 2000,. While duration is useful in certain scenarios, I found myself ...

The AudioPlayer refuses to play following a track change

I am looking to implement an audio player in React Nextjs that features interactive dots, each representing an audio track. The functionality I want is such that clicking on a dot will pause the currently playing track (if any) and start playing the select ...

What is the best way to clear the cache in AngularJS?

It is crucial for the cache to be cleared consistently. However, no matter if a client is created, updated, or deleted, the same result always occurs. Only when I manually delete the cache (Ctrl+Shift+Supr), am I able to view the new data. .factory(' ...

Tips on creating a one-of-a-kind AWS S3 file name

When it comes to sending my file to an s3 bucket via the front end, I've decided that this method seems more efficient based on what I've researched. However, I have encountered a challenge with some of my schemas and collections. Since they are ...

making the div tag invisible when the if statement is satisfied

Is there a way to hide a <div> element if my data equals zero? I have an if condition set up as follows: if ($_SESSION['m1'] == 0) { I want the <div> tag to be deactivated, here is the code snippet for the <div> in question: ...

Vue-Firebase: A guide to linking multiple Firebase services in a single app

I am facing an issue with connecting to two firebases within the same project. In my project, I have two javascript files that connect to each firebase separately, which seems fine. Here is how I import them: import db from '../FireBase' i ...

Is there anything else I should attempt in order to fix this npm start error?

I have been troubleshooting this issue by researching other stack overflow posts, but I continue to encounter the same error message repeatedly. My goal is to execute a Javascript program that incorporates ReactJS. Initially, everything was functioning sm ...

extract all elements from an array nested within another array

I am having difficulty extracting data from an array file in PHP. I was able to read it and convert it into a PHP array, but now I want to display the stored information in a table, however, I keep getting incorrect values. How can I retrieve the informat ...

How to retrieve the chosen row in an angularjs UI-GRID when the row selection event occurs

Within my application, I am utilizing a ui-grid and I am aiming to retrieve the selected row when a user chooses a row from the grid (where only one row can be selected at a time). I have successfully been able to obtain the selected rows through gridApi ...

What is the best way to transmit extra data when tunneling a TLS connection?

I have developed a basic HTTP proxy that utilizes the HTTP CONNECT method for HTTP tunneling. const http = require('http'); const https = require('https'); const pem = require('pem'); const net = require('net'); con ...

Using various colors to highlight specific sections of a letter or number

I am striving to recreate the unique image shown below, particularly interested in achieving the multi-colored effect on the numbers. This aspect of having different colors for parts of the number is intriguing and I would love to learn how it's done. ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

Technique for updating URL when submitting a form on a webpage

I'm a newcomer to the world of coding and I have a simple issue that needs fixing. I want to create a form field where users can input the last segment of a URL provided to them. After entering this segment, I want the page to refresh automatically a ...

Parsley JS: A Solution for Distinct IDs

I have a form that contains multiple select boxes, and I need to ensure that no two select boxes have the same value selected. In simpler terms, if select box 1 is set to value 2 and select box 4 is also set to value 2, an error should be triggered. While ...

Despite successfully connecting to my webservice, the ajax function encounters an error

<script type='text/javascript'> $(document).ready(function () { $("#submit").click(function (e) { e.preventDefault(); var userName = $("#username").val(); var pwd = $("#password").val(); authenticate(use ...

How to include a file within another file in Node.js

When including one JavaScript file into another, I typically use the following syntax: var userControllerObj = require("../controller/userController"), userController = new userControllerObj.UserGatewayController(); I'm curious if I can u ...