How to populate table in Angular with JSON data from a web Service?

Issue

I have a link that displays JSON data when first name is found.

 http://localhost:8080/application/names/find?firstname=f_name&LastName&Address&Status= 

For Example: If I replace f_name with Tim I get this JSON response.

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

If I replace f_name with Sue I get this JSON response.

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

I want to be able to type Tim or Sue and get corresponding data. Here is what I have.

 $http.get('http://localhost:8080/application/names/find?firstname=f_name&LastName&Address&Status=').
  success(function(data) {
 $scope.jsonData = data;
 alert("Success");
}).
error(function(data) {
alert("Invalid URL");
});


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

    $scope.items = $scope.jsonData;

    angular.forEach($scope.items, function (item) {
        if(item.f_name === enteredValue){
            $scope.results.push({
                name: enteredValue,
                address: item.address,
                number: item.phone, 
                status: item.status
            });
        }
    })};

jsp

 <table>
        <tr>
            <td><label>Name:</label></td>
            <td>
    <input id="fName" type="text" data-ng-model="enteredValue" /> 
    <button data-ng-click='clickButton(enteredValue)'>Search</button>
            </td>
        </tr>
  </table>


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

I have been able to populate the dropdown successfully using then such as below.

 $http.get('http://localhost:8080/application/countries').then(function(cdata) 
        {
$scope.countryData = cdata.data;

})

How do I initiate this search? Am I doing this the right way? Do I have to have a service for this?

Solution

looks like your server side function already been able to handle the query and return filtered result, if that’s the case, what you need to do is just to cope with the request url when you send the search result. so, your clickButton function should be something like this:

        $scope.clickButton = function(enteredValue){
        //you may want to change logic here if you got other parameter need to be handled
        var url = 'http://localhost:8080/application/names/find?firstname='+enteredValue+'&LastName&Address&Status=';
        $http.get(url).success(function(data){
        $scope.results = data;
             });
    }

Answered By – lucas

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.