使用 AngularJS 将服务注入控制器 [英] Service injection into controller with AngularJS

查看:31
本文介绍了使用 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

这篇关于使用 AngularJS 将服务注入控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆