Search code examples
angularjs-scopeangularjs-factory

Angularjs view empty/ not pulling data from $scope though controller/factory have the data


I am new to Ionic & Angular and learning it by following the tutorial example here

On running the code, the controller & factory seem to be fetching data correctly but the items are empty. How can I fix the same?

HTML:

<ion-header-bar class="bar-stable">
    <h1 class="title">Page 2!</h1>
</ion-header-bar>
<ion-content class="padding">
    <p>Going to add playlist and video player here</p>
    <ion-list>
            <ion-item class="item-avatar" ng-repeat="item in users">
                <!--changed to ng-src to fix string problem-->
                <img ng-src="{{item.user.picture.thumbnail}}"/>
                <h2>{{item.user.name.first}} {{item.user.name.last}}</h2>
                <p>{{item.user.location.city}} {{item.user.password}}</p>
            </ion-item>
    </ion-list>
</ion-content>

Controller

Added $scope.users=[]; according to here

angular.module('starter.controllers', ['ionic','starter.services'])

.controller('MainCtrl',function(){
  console.log("Main Controller says: Hello World");
})

.controller('PlaylistCtrl',function($scope, userService){
    $scope.users=[];
    userService.getPlaylist().then(function(users){
        $scope.users = users;
        console.log($scope.users);
    });
})

Services

angular.module('starter.services', ['ionic'])

.factory('userService', function($http) {
    return {
        getPlaylist: function(){
            return $http.get('https://randomuser.me/api/?results=10').then(function(response){
                return response.data.results;
            });
        }
    }

})

Here is a screenshot: enter image description here


Solution

  • Hi according to the picture your Values are directly inside the items but in your HTML u mentioned

     <img ng-src="{{item.user.picture.thumbnail}}"/> 
    

    which is wrong there is no user object inside your array so have to call the keys directly like this

    <img ng-src="{{item.picture.thumbnail}}"/>
    

    change your HTML

    <ion-item class="item-avatar" ng-repeat="item in users">
                    <!--changed to ng-src to fix string problem-->
                    <img ng-src="{{item.picture.thumbnail}}"/>
                    <h2>{{item.name.first}} {{item.name.last}}</h2>
                    <p>{{item.location.city}} {{item.password}}</p>
                </ion-item>
    

    enter image description here