服务注入与AngularJS控制器

服务注入与AngularJS控制器

问题描述:

我已经写在AngularJS一个服务,但我不能让它与做事情的角度种子的方式工作。

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

控制器code是如下:

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

您需要定义照片服务:

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

    }]);

一对夫妇引用:

在上面的示例code我使用的参数走样,这是我为了避免问题与缩小您的code时提示。

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

另见的例子在这里:
AngularJS控制器的多种用途和rootScope

和这里Plunker:
http://plnkr.co/edit/Bzjruq

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