-2
<html>

<head>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    <script type="text/javascript">         
     function fetchRecords($http){
        $http.get("http://jsonplaceholder.typicode.com/posts") 
        .then(function (response) {
            this.records = response.data})          
     }
     function recordsCtrl($scope, list){
                $scope.names = list.records 
        }
     var newApp = angular.module('newApp',[])
          newApp.service('list',fetchRecords)
         newApp.controller('recordsCtrl',recordsCtrl)           
         </script>
</head>
<body ng-app="newApp" >
    <div ng-controller="recordsCtrl">
        <table>
            <tr>
                <th>Number</th>
                 <th>id</th>
                  <th>Title</th>
                   <th>Body</th>
            </tr>
            <tr  ng-repeat='name in names' >
                <td>{{name.userId}}</td>
                <td >{{name.id}}</td>
                <td >{{name.title}}</td>
                <td >{{name.body}}</td>
            </tr>
        </table>
     </div>
</body>
</html>

Not able to display records which am getting in response , how to use service in ANgular js ,please let me know . I am trying to keep the $http in custom service and from there I want to pass that response to my $scope . can some one help me

1 Answers1

0

The problem is that you ask for a promise value, but you assign this value before you insure that it is retrieved. You assign $scope.names = list.records, where list.records is not assigned yet. It will be first assigned when the get request receives the response.

So it is better to wrap the $http.get request in a function ex. function getData() that return promises. Then you can use it like this in controller:

list.getDate().then(data => {
  $scope.names = data;
})

Here you can read more about Promises

Jameel
  • 2,926
  • 1
  • 12
  • 11