Service injection into controller with 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
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
链接地址: http://www.djcxy.com/p/77816.html上一篇: AngularJS服务http成功函数使用错误的“this”范围
下一篇: 使用AngularJS将服务注入控制器