使用 AngularJS 将服务注入控制器

使用 AngularJS 将服务注入控制器

问题描述:

我用 AngularJS 编写了一个服务,但我无法让它与 angular-seed 的做事方式一起工作.

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

控制器代码如下:

/*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.

我得到的错误是 Photo 未定义,所以我的猜测是我传递(注入)它的方法是错误的,但我无法找到正确的方法

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

您需要定义Photo服务:

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() {

    }]);

几个参考:

在上面的示例代码中,我使用了参数别名,我建议这样做是为了避免在缩小代码时出现问题.

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

另请参见此处的示例:AngularJS 多次使用 Controller 和 rootScope

这里还有一个Plunker:http://plnkr.co/edit/Bzjruq

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