Angular JS: Service Example

An AngularJS example to share data between controllers using Services.

by Ashish Kumar

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<div class="container">
    <div ng-controller="FormController as formCtrl">
		<table>
            <tbody ng-repeat="country in formCtrl.contryType">
                <tr>
                    <th colspan="2">{{country.country}}</th>
                </tr>
                <tr ng-repeat="city in country.cities">
                    <td>{{city.name}}</td>
                    <td>{{city.rank}}</td>
                </tr>
            </tbody>
        </table>
    </div>
</div>

JavaScript

var app = angular.module("myApp", []);

app.controller("FormController", function () {
	var ctrl = this;

	ctrl.contryType = [{
			"country" : "India",
			"cities" : [{
					"name" : "Bangalore",
					"rank" : "40"
				}, {
					"name" : "Mumbai",
					"rank" : "32"
				}, {
					"name" : "Kolkata",
					"rank" : "54"
				}, {
					"name" : "Chennai",
					"rank" : "42"
				}
			]
		}, {
			"country" : "China",
			"cities" : [{
					"name" : "Guangzhou",
					"rank" : "111"
				}, {
					"name" : "Fuzhou",
					"rank" : "21"
				}, {
					"name" : "Beijing",
					"rank" : "90"
				}, {
					"name" : "Baotou",
					"rank" : "23"
				}
			]
		}
	];
});

angular.bootstrap(document, ['myApp']);