35

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

4

1 回答 1

54

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

于 2013-06-01T20:06:45.743 回答