Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service injection into controller with AngularJS

Tags:

angularjs

I have written a service in AngularJS, but I can't get it to work with the angular-seed way of doing things.

The controller code is as follows:

/*function PhotoCtrl($scope, Photo) {     $scope.photos = Photo.query(); }*/  angular.module('myApp.controllers', []).     controller('PhotoCtrl', [function($scope,Photo) {     $scope.photos = Photo.query(); }]) .controller('MyCtrl2', [function() {  }]); 

Note that the commented out section works fine, but I would like to handle it somewhat like the (recommended) second way.

The error I get is that Photo is undefined, so my guess would be my method of passing (injecting) it is wrong, but I can't find out how to do it correctly

like image 976
Maarten Avatar asked Jun 01 '13 20:06

Maarten


People also ask

Can we inject one controller into another controller in AngularJS?

You can't inject controllers into one another.

Which component Cannot be injected as a dependency in AngularJS controller?

Note that you cannot inject "providers" into run blocks. The config method accepts a function, which can be injected with "providers" and "constants" as dependencies. Note that you cannot inject "services" or "values" into configuration.

Why we use $inject in AngularJS?

It relieves a component from locating the dependency and makes dependencies configurable. It also helps in making components reusable, maintainable and testable. AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.


1 Answers

You need to define the Photo service:

angular.module('myApp.controllers', [])     .service('Photo', ['$log', function ($log) {          return {             query: function() {                 // the query code here.             }         };      }])     .controller('PhotoCtrl', ['$scope', 'Photo', function ($scope, Photo) {         $scope.photos = Photo.query();     }])     .controller('MyCtrl2', [function() {      }]); 

A couple of references:

  • http://docs.angularjs.org/api/angular.Module
  • http://docs.angularjs.org/api/AUTO.$provide#service

In the above sample code I used parameters aliasing, which I suggest in order to avoid issues when minifying your code.

See also an example here: AngularJS multiple uses of Controller and rootScope

And a Plunker here: http://plnkr.co/edit/Bzjruq

like image 175
David Riccitelli Avatar answered Sep 22 '22 08:09

David Riccitelli