AngularJS - 模块间服务

时间:2014-08-20 09:14:01

标签: angularjs

我是Angular的新手,每当我尝试访问我在其他模块的主应用程序顶部声明的服务时,我就会遇到此问题......这就是我声明我的服务的方式......

var myapps = angular.module('myapps',['customDirectives','imgGall','starApp', 'NavBarModel', 'Carousel', 'angular-carousel', 'eXcomments','confirmButton','Status']);

myapps.factory('RateService', function() {
    var ratings = '1';

    return {          
        getRatings : function() {
            return ratings;
        },
        setRatings : function(rate) {
            ratings = rate ;
        }
  };
});

这就是我访问我创建的服务的方式......

var starApp = angular.module('starApp', []);
starApp.controller('StarCtrl', ['$scope', function ($scope, $http, RateService, breadcrumbsService ) {
$scope.rating = 1;
$scope.ratings = [{
    current: 1,
    max: 5
}];


$scope.getSelectedRating = function (rating) {
    RateService.setRatings(rating);
    console.log(rating);
}
}]);

--Some--More--Codes--

我一直在收到这样的错误,说我的setRating未定义?

TypeError: Cannot read property 'setRatings' of undefined
at k.$scope.getSelectedRating (http://localhost/viralenz/themes/viralenz/js/ng.js:242:17)
at http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular.min.js:176:387
at k.N.(anonymous function) [as onRatingSelected] (http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular.min.js:53:175)
at k.scope.toggle (http://localhost/viralenz/themes/viralenz/js/ng.js:275:23)
at http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular.min.js:176:387
at http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular-touch.min.js:11:401
at k.$eval (http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular.min.js:112:15)
at k.$apply (http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular.min.js:112:293)
at HTMLLIElement.<anonymous> (http://localhost/viralenz/themes/viralenz/js/angular-1.2.22/angular-touch.min.js:11:383)
at HTMLLIElement.jQuery.event.dispatch (http://localhost/viralenz/assets/4483d5da/jquery.js:3058:9) angular.js:10046

我做错了什么?

2 个答案:

答案 0 :(得分:1)

应该有

['$scope', '$http', 'RateService', 'breadcrumbsService' , function ($scope, $http, RateService, breadcrumbsService )

你必须正确地#34;内联注释&#34;。

答案 1 :(得分:0)

首先 - 您忘记声明模块依赖:

angular.module('starApp', ['myapps']);

第二 - 您必须将依赖项重复为数组中的字符串:

starApp.controller('StarCtrl', ['$scope', '$http', 'RateService', 'breadcrumbsService', function ($scope, $http, RateService, breadcrumbsService ) {