未知提供者:$ scopeProvider

时间:2015-02-27 11:11:31

标签: javascript angularjs angularjs-scope

我在AngularJS中创建了一个具有 Skinny AngularJS Controllers 的应用程序。该应用程序工作正常,但问题是,当我尝试使用$controller('ControllerOne')访问另一个控制器时,我收到以下异常。

JSFiddle

Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope
http://errors.angularjs.org/1.2.1/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:78:12
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3451:19
    at Object.getService [as get] (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3578:39)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3456:45
    at getService (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3578:39)
    at invoke (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3600:13)
    at Object.instantiate (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3636:23)
    at $get (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:6639:28)
    at new <anonymous> (http://fiddle.jshell.net/_display/:47:22)
    at invoke (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:3624:28)

我的代码如下所示

var mainApp = angular.module('mainApp', ['firstApp', 'secondApp']);

var firstApp = angular.module('firstApp', []);
firstApp.controller('ControllerOne', function ($scope) {
    this.name = "Messi";
});

var secondApp = angular.module('secondApp', []);
secondApp.controller('ControllerTwo', function ($scope, $controller) {
    $scope.ctrlOne = $controller('ControllerOne');
});

任何人都可以告诉我一些解决方案吗

2 个答案:

答案 0 :(得分:1)

$controller将实例化控制器。

您需要将范围传递给它。

ctrl1 = $controller('ControllerOne', {$scope: $scope})

这是更新的小提琴。 http://jsfiddle.net/oqnrrL8y/1/

答案 1 :(得分:1)

不确定这是一个非常好的想法,就像你正在做的那样,但这是一个解决方案:

secondApp.controller('ControllerTwo', function ($scope, $controller) {
    $scope.ctrlOne = $controller('ControllerOne', {$scope: $scope});
});

问题是根据ControllerOne的定义,它期望一个依赖注入服务:$scope。所以你需要提供这项服务。

演示: http://jsfiddle.net/oqnrrL8y/2/