我是Angular的新手,并尝试进行基本的依赖注入以获得它的悬念。在这个例子中,我尝试依赖注入一个服务到控制器,我收到以下错误。
Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- testInjection
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.0-rc.1/angular.js" data-semver="1.4.0-rc.1"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
</body>
</html>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['testInjection',function($scope) {
$scope.name = 'World';
}]).factory('testInjection', ['$scope', function($scope) {
}]);
答案 0 :(得分:0)
你应该这样做:
app.factory('testInjection', ['$scope', function($scope) {
}]);
app.controller('MainCtrl', ['$scope', 'testInjection',function($scope, testInjection) {
$scope.name = 'World';
}]);
之前定义您的服务(工厂)会更好。 这里的问题是,即使在服务中注入了作用域,你也必须在控制器中再次注入它。
答案 1 :(得分:0)
正如Nikos所说,不要试图将范围对象注入服务或工厂。
对于我的角度项目,我为每个控制器/服务/工厂/指令创建一个新文件。这些文件的设置如下所示:
工厂:
(function () {
'use strict';
angular.module('MyModule')
.factory('someService', function () {
var service = {
myFunction: function () {
return "Hello";
}
};
return service;
});
})();
控制器:
(function () {
'use strict';
angular.module('MyModule')
.controller('someCtrl', ['$scope', 'someService', function ($scope, someService) {
$scope.name = "World";
$scope.message = someService.myFunction() + " " + $scope.name;
}]);
})();
请注意,上述语法仅检索现有模块。请参阅“创建与检索”下的Angular Modules。我有另一个文件,它使用相同的语法创建模块,但使用括号导入其他模块。
您应该查看angular docs以获取更多信息和示例。
答案 2 :(得分:0)
我修改了你的弹药here。请检查您定义服务的方式以及注入方式。即使您在控制器之后定义它也没关系。此外,错误是因为您的工厂功能没有返回任何东西。修正了这一点。
您的代码应如下所示:
var app = angular.module('plunker', []);
app.controller('MainCtrl'['$scope','testInjection',function($scope,testInjectio)
{
$scope.name = testInjection;
}]).factory('testInjection', function() {
return "ABC"
});