Sole
Sole

Reputation: 3340

Ionic app - controller $http

I am building a app in ionic, i am trying to get external restful api data into the view via a controller, but there seems to be something wrong with my controller because nothing is being pulled in?

my code is:

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

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.controller('myCtrl', function($scope, $http) {
$http.get('http://jsonplaceholder.typicode.com/posts').then(function(results){
  $scope.posts = results.data.posts;
  }, function(err) {
    console.error('ERR', err);
    // err.status will contain the status code
  })
});
 <ion-content class="has-subheader" ng-controller="myCtrl">
      <ion-list>
        <ion-item ng-repeat='item in posts' class="item-thumbnail-left item-text-wrap">
          <img src="http://placehold.it/100x100" alt="photo">
          <h2>{{post.title}}</h2>
          <h4>Place</h4>
          <p style="font-size:12px; line-height:16px;">Quisque quis sem a velit placerat vehicula quis nec felis. Mauris posuere, nisl vitae condimentum luctus, tellus enim blandit orci, quis efficitur nibh libero eget dui. Aliquam fermentum velit quis sem molestie.</p>

        </ion-item>
      </ion-list> 
    </ion-content>

Any help would be appreciated.

Upvotes: 1

Views: 158

Answers (2)

Mohamad Al Asmar
Mohamad Al Asmar

Reputation: 1177

you have made 2 mistakes in your code:

First: once you define 'item' in ng-repeat you should use it to bind your object key "title":

ng-repeat='item in posts' 

'item' is now holding your JSON keys.

<h2>{{item.title}}</h2>

Second: reviewing jsonplaceholder JSON you are calling through this url, http://jsonplaceholder.typicode.com/posts, title key is under results.data , so you should define posts like this:

$scope.posts = results.data

For more help: I've taken the code you provided and made it working on a plunk, check it on the following url: http://embed.plnkr.co/Gp1U3y/preview

Please contact me for more help. Thanks

Upvotes: 0

carton
carton

Reputation: 1168

Solution to this:

$http.get('http://jsonplaceholder.typicode.com/posts')
.success(function(results){
    $scope.posts = results.posts;
    console.log($scope.posts);
});

You were using data but there isn't data in the results. Look at the console, and you should see objects now.

Working codepen

Upvotes: 1

Related Questions