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
You can't inject controllers into one another.
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.
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.
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With