2

I want to get an array of JSON objects from a return function and loop inside this array using ng-repeat, but its not working for me.

This is my code :

var app=angular.module("myApp",[]);
    
app.controller("myController",function($scope,$http){
    
  $scope.listOfFields=[];
        
  $scope.getlistOfFieldsByIdTable = function(idTable)
  {
    $http.get("/listOfFieldsByIdTable/"+idTable)
         .success(function(data){
             return data;
         });
    };
         
});
<!-- first call  -->
<!-- 150 is the id of the table-->
<div class="panel-body" ng-app="myApp" ng-controller="myController">
                
  <ul ng-init="listOfFields = getlistOfFieldsByIdTable(150)"> 
    <li ng-repeat="field in listOfFields ">
      {{field.name}}
    </li>
  </ul>                           
</div>
    
<!-- second call  -->
    
<div class="panel-body" ng-app="myApp" ng-controller="myController">
  <ul>
    <li ng-repeat="field in getlistOfFieldsByIdTable(150)">
      {{field.name}}
    </li>
  </ul>
</div>

The two calls that I used are not working for me, my service works fine when i used a RestClient like "Advanced Rest Client plugin in Google Chrome".

How can I property call my array of objects and show the results in my HTML page?

4
  • Log your results in your get function. Do you get anything? Commented Apr 3, 2016 at 13:12
  • hey @JeremyJackson thanks for your response, yes i used a function(error) { console.log('something went wrong'); }); but i don't get any error inside the function, my problem in the manner of rendering the result on my HTML page :( Commented Apr 3, 2016 at 13:42
  • That's fine, but try logging the response you get back, not just an error. Just wanna be sure that you're actually getting data back to render. Also, try calling the function in your console and see if you get anything back as well. Commented Apr 3, 2016 at 13:49
  • hey @JeremyJackson i used console.log("length of my data is : "+data.length); and it gives me length of my data is : 21 , this is right i have 21 records in my database with id 150 that i used in my request , so now i am sure that a have a problem in my why of rendering data in HTML , any suggestion please about my code in the HTML page? Commented Apr 3, 2016 at 14:25

2 Answers 2

1

The problem is with the getlistOfFieldsByIdTable function:

   //WRONG
    $scope.getlistOfFieldsByIdTable = function(idTable)
        {
           $http.get("/listOfFieldsByIdTable/"+idTable)
           .success(function(data){

             return data;
           });
        };

The return data statement returns data to the anonymous function inside the .success method. It does not return data to the parent function. Since no return is specified at the parent level, the value returned is null. A return needs to be done at every level of the nesting.

//BETTER
$scope.getlistOfFieldsByIdTablePromise = function(idTable) {

    var promise = $http.get("/listOfFieldsByIdTable/"+idTable);

    var derivedPromise = promise.then( function onfulFilled(response) {
        var data = response.data;
        //Sets scope value asynchronously
        $scope.listOfFieldsByIdTable = data;
        //return value creates derived promise
        return data;
    };

    return derivedPromise;
};

In this example there is a return statement at every nested level but the final item returned is not a value; it is a promise.

The $http service only returns promises. And the methods attached to a promise object only return promises. Data goes on scope only as a side effect and the operation happens in the future when the XHR completes.


in my ng-repeat , i should use listOfFieldsByIdTable or derivedPromise that you used in the return function?

In the ng-repeat directive use the $scope.listOfFieldsByIdTable variable. The ng-repeat directive puts a $watch on the variable which checks for changes every digest cycle and when the data appears (or changes), it updates the DOM.

To do additional processing of the data in the controller, chain from the derived promise.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your time and your response , i have one question, about your example, in my ng-repeat , i should use listOfFieldsByIdTable or derivedPromise that you used in the return function? thanks in advanced
Use $scope.listOfFieldsByIdTable. See update for additional explaination.
0

When you are performing some asynchronous operations, you can't return data, so you have to deals with callbacks and/or promises.

For example, we can create a service, with a method which return a promise :

  function Service($http) {

      this.getData = () => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve([1,2,3,4,5]);
          }, 1000);
        });
      }

  }

And then use this service in a controller like this :

  function Controller($scope, Service) {

    //Initialize our list
    $scope.list = [];

    //Call our promise
    Service.getData().then((response) => {
      //After 1s, retrieve the data 
      $scope.list = response
      //Update the bindings
      $scope.$apply();
    });

  }

You can see the Working Plunker

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.