Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting data from a json file in IONIC using AngularJS

Problem

I created my first project with ionic framework using ionic tabs template and this is an example of the project : (https://github.com/driftyco/ionic-starter-tabs) As we see in this project we get a list of friends and a friend detail from an array list created in the services.js file, but I want to get this list and items detail from a json file like this(example https://friends.json).

Question

How can I Pull JSON data from a web server down to my app??

like image 883
Widad Avatar asked Dec 01 '25 05:12

Widad


1 Answers

Factory in services.js

Start off with a factory but replace my url wit yours.

.factory('Friends', function ($http, $rootScope, $stateParams) {

  return {
    all: function () {
      return $http.get('https://friends.json/all', { params: { user_id: $rootScope.session } })
    },
    get: function () {
      return $http.get('https://friends.json/getOne', { params: { user_id: $rootScope.session, chat_id: $stateParams.idchat } })
    },
    add: function (id) {
      return $http.get('https://friends.json/new', { params: {idfriends:id}})
    }
  };
});

Controller in controllers.js

Then make a controller like this. This is when you instantiate the factory to get your data.

.controller('FirendsCtrl', function ($scope, Friends) {

  Friends.all().success(function (response) {
    $scope.friends = response;
  })
})

Scope added to View

This will bind the data to the scope. And there for make it available to the view.

Finally you will be able to bring the data to the view via $scope I have created a list here of all the friends that you get from get friend with a nice side swip to add more or delete.

<ion-view view-title="Contacts">
  <ion-content>
  <ion-list>
      <ion-item class="item-icon-right" ng-repeat="data in friends">
          <h1>{{ data.username }}</h1>
          <p>{{ data.friendNumber}}</p>
          <i class="icon ion-chevron-left icon-accessory"></i>
          <ion-option-button class="button-positive" ng-click="viewFriend(viewFriend(data.idfriends))">View Friend</ion-option-button>
          <ion-option-button class="button-assertive" ng-click="deleteFriend(remove(data.idfriends))">Delete</ion-option-button>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

Disclaimer

this is some code that I had previously written, I've modified it a bit to fit with your question. I have not ran this version exactly but my full version works fine.

if you wish to see the full code please feel free to check out my github repo https://github.com/joeLloyd/Scripto5000

like image 159
Joe Lloyd Avatar answered Dec 03 '25 19:12

Joe Lloyd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!