Example 1: Show Company Background With Simple $http.get()
This example will show you how to get JSON data from Restful server by using $http.get(), you can download the ionic workspace here. Let’s create a new app by “ionic start itBlogsApp sidemenu” under C:/workspace_ionic/ , it will generate the new project – itBlogsApp. Enter “Y” to create the ionic.io account and please register, because we will demonstrate sending Push Notifications in Example – Showing Promotion With QR Code and Push Notification
It will auto-popup the browser with this webpage, just simply fill in the information and sign up.
After that, you should find a new folder called “itBlogsApp” under C:/workspace_ionic/ . Please follow below steps:
- Update C:\workspace_ionic\itBlogsApp\www\js\app.js , add below code after .state(‘app’
.state(‘app.home’, { url: ‘/home’, views: { ‘menuContent’: { templateUrl: ‘templates/home.html’, controller: ‘HomeController’ } } })
And update $urlRouterProvider.otherwise(‘/app/playlists’); to $urlRouterProvider.otherwise(‘/app/home’);
- Update C:\workspace_ionic\itBlogsApp\www\css\style.css, add the this code
h3 { padding: 10px; }
p { padding: 0 10px; }
- Update C:\workspace_ionic\itBlogsApp\www\templates\menu.html, add the this code
<ion-item menu-close href=”#/app/home”>Home</ion-item>
after
<ion-item menu-close ng-click=”login()”>Login</ion-item>
- Update C:\workspace_ionic\itBlogsApp\www\js\controllers.js , adding below code after .controller(‘AppCtrl’, function($scope, $ionicModal, $timeout)
.controller(‘HomeController’, function($scope, $http, $stateParams) {
$scope.getData = function() {
$http.get(“http://localhost:8080/SpringRestfulExample/company”)
.success(function(data, status) {
$scope.name = data[0].name;
$scope.background = data[0].background;
})
.error(function(data, status) {
console.log(‘HomeController Error…’, status);
});
};
$scope.getData();
})
- Finally, adding home.html to C:\workspace_ionic\itBlogsApp\www\templates\ . Please find below home.html code:
<ion-view view-title=”{{name}}”>
<ion-content>
<h3>{{name}}</h3>
<p>{{background}}</p>
</ion-content>
</ion-view>
Ok, we have updated all codes, let’s try to run it and see what happen. Before running the IONIC app, please make sure the Restful server is running right now with port 8080.
Then, please go to the command prompt, and enter “ionic serve –p 8181”
It will pop-up a browser showing this page:
Done, the texts “IT-Blogs.com” and “Welcome to IT-Blogs.com … Feel free to check with our latest promotions and products.” are getting from Restful server via JSON api, and showing on the home page.