An AngularJS module can contain one or more services. In order to make use of a service we need to make use of the Angular dependency injection mechanism, which involves the following:
- Identifying the relevant module through the AngularJS.org API section.
- Adding a script tag to our HTML page.
- Declaring the module as a dependency when calling the angular.module function.
- Passing the needed service names as arguments to the controller function.
The following shows the addition of script tags referencing the messages and resource modules:
<!DOCTYPE html> <html lang="en-us" ng-app="myApp"> <head> ... <!-- load angular via CDN --> <script src="//code.angularjs.org/1.3.0-rc.1/angular.min.js"></script> <script src="//code.angularjs.org/1.3.0-rc.1/angular-messages.min.js"></script> <script src="//code.angularjs.org/1.3.0-rc.1/angular-resource.min.js"></script> <script src="app.js"></script> </head> ...
In the app.js file we can see that the modules ngMessages and ngResources have been declared as dependencies in the angular.module function and the needed services are being passed as arguments to the controller function; in this case, $log, $filter, and $resource.
var myApp = angular.module('myApp', ['ngMessages', 'ngResource']); myApp.controller('mainController', function($scope, $log, $filter, $resource) { ... });
The main AngularJS API page contains information about the modules available: https://docs.angularjs.org/api.
One problem that we have with the controller function above is that the variable names provided in the argument will be changed if processed through a code minifier. The change in variable names will break the service injection and will cause errors. In order to avoid this issue, AngularJS provides a second way to create a controller which involves passing an array instead of a function. The last element of the array is the controller function. The other array elements are variable name strings that AngularJS will resolve and pass as arguments to the function.
var myApp = angular.module('myApp', []); myApp.controller('mainController', ['$scope', '$log', function($scope, $log) { console.log($scope); }]);