AngularJS dependency injection

The arguments of injectable functions like controller constructors are order-independent.

app.controller('appController', function ($scope, appFactory) { });
// same as
app.controller('appController', function (appFactory, $scope) { });

js:

var app = angular.module('app', []);
 
app.factory('appFactory', function () {
	var factory = {};
	var countriesList = [
		{name: 'Germany', capital: 'Berlin', population: '81,305,856'},
		{name: 'France', capital: 'Paris', population: '65,630,692'},
		{name: 'Italy', capital: 'Rome', population: '61,261,254'},
		{name: 'Spain', capital: 'Madrid', population: '47,042,984'},
		{name: 'United Kingdom', capital: 'London', population: '63,047,162'}
	];
 
	factory.getCountries = function () {
		// can use $http object to retrieve remote data in a "real" app
		return countriesList;
	};
	return factory;
});
 
app.controller('appController', ['$scope', 'appFactory', function ($scope, appFactory) {
	$scope.countriesList = [];
 
	init();
	function init() {
		$scope.countriesList = appFactory.getCountries();
	}
 
}]);

html:

<section ng-app="app" class="container">
	<section ng-controller="appController">
		<h3>List of countries</h3>
		<ul>
			<li ng-repeat="country in countriesList">
				{{country.name}} - {{country.capital}}
			</li>
		</ul>
	</section>
</section>

Leave a Reply

Your email address will not be published. Required fields are marked *