Search code examples
javascriptjsonangularjsangular-ngmodel

How to populate table with json data using angular?


I have loaded the json data successfully via http but having a problem populating a table with this json data based on the entered value 'name'. Plunker Below.

Plunker

json

   [
    {
        "name": "Tim",
        "address": "Road",
        "phone": "1234",
        "status": "busy"
    },

    {
        "name": "Sue",
        "address": "Street",
        "phone": "4321",
        "status": "available"
    }
  ]

Assuming my controller and app are defined correctly what am I doing wrong? I want to type Tim or type Sue and populate the table with corresponding data.

angular.js

 $http.get('data.json').
     success(function(data) {
      $scope.jsonData = data;
        alert("Success");
     }).
     error(function(data) {
        alert("Invalid URL");
   });

   $scope.clickButton = function(enteredValue) {

    $scope.items = $scope.jsonData;

    angular.forEach($scope.items[enteredValue], function (item, key) {
        $scope.results.push({
                 name: enteredValue,
                 address: item.address,
                 phone: item.phone, 
                 status: item.status
             });

 });

jsp

 <table>
        <tr>
            <td><label>Name:</label></td>
  <td>
    <input id="pName" name="pName" type="text" data-ng-model="enteredValue" /> 
            </td>
        </tr>

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


 <table>
       <tr data-ng-repeat="result in results">
        <td data-title="'ID'">{{result.status}}</td>
        <td data-title="'Name'">{{result.name}}</td>
        <td data-title="'Status'" >{{result.address}}</td>
        <td data-title="'Start Date'" >{{result.phone}}</td>
      </tr>
 </table>

Solution

  • Try this, the problem is that in the json file, the enteredValue (someone's name in this case) is not a valid key in the object, so angulars foreach will never execute because your $scope.items[enteredValue] is always undefined:

    $http.get('data.json')
    .success(function(data) {
        $scope.jsonData = data;
        alert("Success");
    })
    .error(function(data) {
        alert("Invalid URL");
    });
    
    $scope.clickButton = function(enteredValue) {
    
        $scope.items = $scope.jsonData;
    
        angular.forEach($scope.items, function (item) {
            if(item.name === enteredValue){
                $scope.results.push({
                    name: enteredValue,
                    address: item.address,
                    phone: item.phone, 
                    status: item.status
                });
            }
        });
    };
    

    I've updated your plunkr: http://plnkr.co/edit/YRo8SugTDQ54NIvUHDVy