Using services as dependencies for controllers is very similar to using services as dependencies for another service.
Since JavaScript is a dynamic language, DI can't figure out which services to inject by static
types (like in static typed languages). Therefore, you must specify the service name by using the
$inject
property, which is an array containing strings with names of services to be injected.
The name must match the corresponding service ID registered with angular. The order of the service
IDs matters: the order of the services in the array will be used when calling the factory function
with injected parameters. The names of parameters in factory function don't matter, but by
convention they match the service IDs.
function myController($loc, $log) { this.firstMethod = function() { // use $location service $loc.setHash(); }; this.secondMethod = function() { // use $log service $log.info('...'); }; } // which services to inject ? myController.$inject = ['$location', '$log'];
<script type="text/javascript"> angular. module('MyServiceModule', []). factory('notify', ['$window', function(win) { var msgs = []; return function(msg) { msgs.push(msg); if (msgs.length == 3) { win.alert(msgs.join("\n")); msgs = []; } }; }]); function myController(notifyService) { this.callNotify = function(msg) { notifyService(msg); }; } myController.$inject = ['notify']; </script> <div ng:controller="myController"> <p>Let's try this simple notify service, injected into the controller...</p> <input ng:init="message='test'" type="text" ng:model="message" /> <button ng:click="callNotify(message);">NOTIFY</button> </div>
it('should test service', function() { expect(element(':input[ng\\:model="message"]').val()).toEqual('test'); });
Understanding Angular Services Creating Angular Services Managing Service Dependencies Testing Angular Services