服务不会注入控制器

时间:2015-02-20 12:14:42

标签: javascript angularjs ionic-framework angular-services angularjs-factory

我过去曾做过一些Angular应用程序,但从未真正使用过模块。我现在正在创建一个Ionic应用程序(使用Angular),由于某种原因,我无法将我的服务注入到控制器中。

controllers.js

angular.module('myapp.controllers', [])
.controller('StreamCtrl', ['$scope', 'StreamService',
function($scope, StreamService) {
    $scope.playlists = [1,2,3,4];
}]);

services.js

angular.module('myapp.services', [])
.factory('StreamService', ['$scope', function($scope) {
    var self = {
        'fetching' : false,
        'streamItems' : []
    };
    return self;
]);

app.js

angular.module('myapp', ['ionic',
                        'myapp.services',
                        'myapp.controllers',
                        'ngCordova',
                        'LocalStorageModule'])
// And lots of other code that isn't needed for this question.

因此,当我尝试加载StreamCtrl时,我最终收到以下错误:

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <-StreamService
http://errors.angularjs.org/1.3.6/$injector/unpr?p0=<ion-nav-view name="menuContent" class="view-container" nav-view-transition="ios">copeProvider%20%3C-%20%24scope%20%3C-%20StreamService
at REGEX_STRING_REGEXP (http://localhost:8100/lib/ionic/js/ionic.bundle.js:7888:12)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:11806:19
at Object.getService [as get] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11953:39)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:11811:45
at getService (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11953:39)
at Object.invoke (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11985:13)
at Object.enforcedReturnValue [as $get] (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11847:37)
at Object.invoke (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11994:17)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:11812:37
at getService (http://localhost:8100/lib/ionic/js/ionic.bundle.js:11953:39)

2 个答案:

答案 0 :(得分:5)

请参见此工作fiddle

您正在将服务视为控制器,从不将$scope注入服务,而不是

var myApp = angular.module('myApp',['myapp.services','myapp.controllers']);

angular.module('myapp.controllers', [])
.controller('StreamCtrl', ['$scope', 'StreamService',
function($scope, StreamService) {
    $scope.playlists = [1,2,3,4];
}]);

angular.module('myapp.services', []).factory('StreamService',  function() {
    var self = {
        'fetching' : false,
        'streamItems' : []
    };
    return self;}
);

答案 1 :(得分:3)

您的错误清楚地表明StreamService工厂内存在问题。

你永远不能在$scope内注入factory。删除$scope依赖项将解决您的问题。

工厂主要用于公开单例方法,常用和可共享数据。通常我们编写任何服务调用或方法,任何使用其依赖性注入它的模块都可以访问它。

<强>工厂

angular.module('myapp.services', [])
.factory('StreamService', [function() {
    var self = {
        'fetching': false,
        'streamItems': []
    };
    return self;
}]);

Working fiddle

希望这可以帮到你。感谢。