我试图在使用$ controller服务创建的控制器中注入$ scope。
我收到以下错误: 未知提供商:$ scopeProvider< - $ scope< - TestController
重要的是要提到创建发生在指令的链接功能中。
我写了一个简单的例子来说明错误。
app.js:
(function() {
angular.module('app', [])
.controller('TestController', [
'$scope',
function($scope) {
// I want to be able to use 'message' from the directive's template
// as if the controller was loaded directly using ng-controller
$scope.message = 'Hello World!';
}
])
.directive('directive', [
'$controller',
function($controller) {
return {
restrict: 'A',
template: '<div>{{ message }}</div>',
link: function(scope) {
// In the actual app the controller is dynamically selected
// I'm registering a $watch here that provides me the
// name of the controller
scope.myController = $controller('TestController');
}
};
}
]);
})();
的index.html:
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Testing injection</title>
</head>
<body>
<div directive></div>
<script src="angular.js"></script>
<script src="app.js"></script>
</body>
</html>
问题:为什么会这样?你能解释一下这种行为背后的逻辑吗?任何解决方法?
谢谢。
答案 0 :(得分:0)
根据Digix的回答,我能够让它发挥作用:
var locals = {};
locals.$scope = scope;
$controller('TestController', locals);
我的假设是,通过这种方式,控制器不会创建新的范围,而是共享指令之一。
答案 1 :(得分:-2)
var locals = {};
locals.$scope = scope.$new();
$controller('testCtrl', locals);