将服务注入控制器会引发错误

时间:2017-07-07 17:08:56

标签: javascript angularjs model-view-controller

我无法将服务注入控制器。一年前我能够执行类似的代码并且它有效,但这次我运气不好。

app.js

'use strict';
var app = angular.module('product', [
  "ngRoute",
]);

main.ctrl.js

'use strict';
app.controller('mainCtrl', ['$scope','$http','srv', function ($scope,$http,srv) {
    var srvUrl = srv.getSrvUrl;
    var data = srv.getData(1,2);
}]);

srv.js

app.service("srv", function ($http,$scope) {
    this.getSrvUrl = "http://127.0.0.1/api/";
    this.getData = function(a,b) { return a*b; }
});

的index.html

<!--JS-->
<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>
<!--APP-->
<script type="text/javascript" src="app/app.js"></script>
<!-- ROUTE -->
<script type="text/javascript" src="bower_components/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="app/routes/app.route.js"></script>
<!-- SERVICE -->
<script type="text/javascript" src="app/services/srv.js"></script>
<!--CONTROLLER-->
<script type="text/javascript" src="app/controllers/main.ctrl.js"></script>

控制台错误

angular.js:14362 
Error: [$injector:unpr] http://errors.angularjs.org/1.6.2/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20srv
at angular.js:38
at angular.js:4650
at Object.d [as get] (angular.js:4803)
at angular.js:4655
at d (angular.js:4803)
at e (angular.js:4828)
at Object.instantiate (angular.js:4874)
at Object.<anonymous> (angular.js:4712)
at Object.invoke (angular.js:4862)
at Object.$get (angular.js:4696)

请帮忙。

2 个答案:

答案 0 :(得分:2)

您无法在服务中注入$scope

服务是用于共享数据的单例对象和一些可重用的方法。

应该是这样的

app.service("srv", function ($http, $scope) {
    return {
        getSrvUrl: "http://127.0.0.1/api/",
        getData: function (a, b) { return a * b; }
    }
});

答案 1 :(得分:1)

您可以在服务中注入的唯一范围是echo "<a href='imageInfo.php?id=".$image_id."'>LINK</a>"; (但考虑到您的代码,我不确定您是否需要服务中的范围)。此外,您可能希望将服务名称添加为缩小字符串:

$rootScope