Memunculkan hasil request JSON di IONIC
Terus terang saya baru nyentuh ionic dan cordova serta angularnya. Tapi karena tuntutan pekerjaan mesti cepat untuk belajar jadi to the point pada masalah bagaimana menyelesaikannya. Jadi ceritanya pengen ngambil data dari database lewat API yang menghasilkan JSON. So, langsung cari-cari cara nangkep tu JSON untuk ditampilkan ke IONIC. ketemu di alamat :
http://10minbasics.com/ionic-http-get-json/
dan
http://plnkr.co/edit/Wuc6M7?p=preview
Ok, saya coba kombinasikan berikut cara-caranya
Buat dulu app ionic dengan cara ionic start myApp tabs
lalu cari www/js/controllers.js . Nah, di file itu ubah saja DashCtrl nya
.controller(‘DashCtrl’, function($scope,$http) {
$scope.result = “”;
$http.get(‘todos.json’)
.success(function(data, status, headers,config){
console.log(‘data success’);
console.log(data); // for browser console
$scope.result = data; // for UI
})
.error(function(data, status, headers,config){
console.log(‘data error’);
})
.then(function(result){
things = result.data;
});
})Lalu pada contoh ini buat file todos.json yang saya letakkan pada www/todos.json isinya
[{ “text”:”learn angular”, “done”:true },
{ “text”:”build an angular app”, “done”:false},
{ “text”:”something”, “done”:false },
{ “text”:”another todo”, “done”:true }]Lanjut, buka www/templates/tab-dash.html lalu tambahin kode berikut, terserah mau dibaris keberapa, kalau saya di baris ke 16. Jadi full code tab-dash.html nya jadi seperti ini:
<ion-view view-title=”Dashboard”>
<ion-content class=”padding”>
<h2>Welcome to Ionicsa</h2>
<p>
This is the Ionic starter for tabs-based apps. For other starters and ready-made templates, check out the <a href=”http://market.ionic.io/starters" target=”_blank”>Ionic Marketer</a>.
</p>
<p>
To edit the content of each tab, edit the corresponding template file in <code>www/templates/</code>. This template is <code>www/templates/tab-dash.html</code>
</p>
<p>
If you need help with your app, join the Ionic Community on the <a href=”http://forum.ionicframework.com" target=”_blank”>Ionic Forum</a>. Make sure to <a href=”http://twitter.com/ionicframework" target=”_blank”>follow us</a> on Twitter to get important updates and announcements for Ionic developers.
</p>
<p>
For help sending push notifications, join the <a href=”https://apps.ionic.io/signup" target=”_blank”>Ionic Platform</a> and check out <a href=”http://docs.ionic.io/docs/push-overview" target=”_blank”>Ionic Push</a>. We also have other services available.
<li ng-repeat=”todo in result”>
{{todo.text}} — <em>{{todo.done}}</em>
</li>
</p>
</ion-content>
</ion-view>
Dah gitu aja, save lalu coba jalankan dengan
ionic serve
Selesai……
Catatan:
oya, untuk file todos.json bisa diganti url tempat kita akan mengembil file jsonnya.
Satu lagi, kalau anda mengambil json dari suatu alamat web, di phpnya cross origin resource sharing diaktifkan dulu dengan menambahkan
<?php
header("Access-Control-Allow-Origin: *");