Ajax request in app.js
1 2 3 4 5 6 7 8 9 10 |
var app = angular.module('myApp', []); app.controller('java2blogContoller', function($scope,$http) { var url = "countries.json"; $http.get(url).success( function(response) { $scope.countries = response; }); }); |
 Lets see complete example:
 Project structure:
Step 1: Create dynamic web project named “AngularJSAjaxExample” in eclipse.
Step 2: We are going to read counties.json from server. Create countries.json in WebContent folder with below json text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
[ { "id": 1, "countryName": "India", "population": 10000 }, { "id": 2, "countryName": "Bhutan", "population": 7000 }, { "id": 3, "countryName": "Nepal", "population": 8000 }, { "id": 4, "countryName": "China", "population": 20000 } ] |
Step 3: Create angularJSAjaxExample.html in WebContent folder as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<meta charset="UTF-8"> <title>Angular js</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script> <script src="app.js"></script> <link rel="stylesheet" type="text/css" href="table.css"> <div ng-app="myApp" ng-controller="java2blogContoller"> <table border="1"> <thead> <tr> <th>ID</th> <th>Country Name</th> <th>Population</th> </tr> </thead> <tr ng-repeat="con in countries"> <td> {{ con.id }}</td> <td> {{ con.countryName }}</td> <td>{{ con.population }}</td> </tr> </table> </div> |
Here we are using ng-repeat tag to iterate counties list and showing it in table.
Step 4 : Create app.js in WebContent folder as below:
1 2 3 4 5 6 7 8 9 10 11 |
var app = angular.module('myApp', []); app.controller('java2blogContoller', function($scope,$http) { var url = "countries.json"; $http.get(url).success( function(response) { $scope.countries = response; }); }); |
Step 5: We are going to apply style on this table, so create table.css as below in WebContent folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
table { font-family: "Helvetica Neue", Helvetica, sans-serif } caption { text-align: left; color: silver; font-weight: bold; text-transform: uppercase; padding: 5px; } thead { background: SteelBlue; color: white; } th, td { padding: 5px 10px; } tbody tr:nth-child(even) { background: WhiteSmoke; } tbody tr td:nth-child(2) { text-align:center; } tbody tr td:nth-child(3), tbody tr td:nth-child(4) { text-align: right; font-family: monospace; } tfoot { background: SeaGreen; color: white; text-align: right; } tfoot tr th:last-child { font-family: monospace; } |
Step 6: Run the html file on the server. Right click on “angularJSAjaxExample.html” and go to run -> run on server.
You will see below output:
URL: http://localhost:8080/AngularJSAjaxExample/angularJSAjaxExample.html