Ray
Ray

Reputation: 780

Why my ng-repeat is not working?

I am trying to display items resided in a remote database by executing the following code that I have in services.js:

.factory('Users', ['$http', function($http) {
    var res = $http.post("http://mydomain/API.php?requestType=Location_Search", { "search": "my search"} );

    return {
        all: function() {
          return res;
        },
        get: function(id) {
            for (var i = 0; i < res.length; i++) {
                  if (res[i].U_ID === parseInt(id)) {
                      return res[i];
                  }
            }
            return null;
        }
    };
}]);

I tried to print the result in console and it is returning the correct rows. Then, my controller is assigning the result of my previous factory function to a variable called MYRESULT like the following:

.controller('DashCtrl', function($scope, Users) {
    $scope.MYRESULT = Users.all();
    //console.log(Users.all()); it is returning the correct rows
})

Now, everything should be ok and my JSON array is in MYRESULT variable. However, in my view I am calling the ng-repeat directive to loop through each item of my JSON array but I am getting nothing. My html code is like the following:

<ion-content class="has-subheader">
        <ion-list>
            <ion-item class="item-thumbnail-left item-text-wrap" 
                      ng-repeat="item in MYRESULT " 
                      href="#/tab/dash/{{item.U_ID}}">
                <img ng-src="http://mydomain/Uimg/{{item.U_ID}}.jpg" />
            </ion-item>
        </ion-list>
</ion-content>

Can anybody tell me what's wrong with my code. As I believe, my mistake should be in the view because as I mentioned before the JSON array in the console is correct.

Note: DashCtrl is the controller of my tab.

Thanks!!

Upvotes: 0

Views: 263

Answers (1)

yuka_mustang
yuka_mustang

Reputation: 100

That's because the post, as every other method, is returning a promise. You should chain the .then() function and get the result from there.

Doc: https://docs.angularjs.org/api/ng/service/$http#post

Example:

$http.post("mydomain/API.php?requestType=Location_Search";, { "search": "my search"} )
.then(
    function(response) {
        // response is what you actually want
        $scope.MYRESULT = response;
    },
    function(errorResponse) {
        // this second function is not mandatory, it's called if the server responds with an error status. If this function is not provided, all responses will be caught by the first function
    }
);

Upvotes: 2

Related Questions