2016-08-17 53 views
0

运行我的测试情况下的这段代码是给错误。

beforeEach(module(function($scope) { 

// do something interesting with the service 
//console.log($controller); 

})); 

控制台出现错误。

debug.js:21 Uncaught Error: [$injector:modulerr] Failed to instantiate  
module function ($scope) due to: 
Error: [$injector:unpr] Unknown provider: $scope 

任何人都可以请解释为什么它是不能够找到$范围。如果我将它更改为$ timeout或$ controller,它也不起作用。

更新的代码 如果我更改代码以这种

然后它

module(function($controllerProvider) { 
// we could also access the $controllerProvider.allowGlobals() function, 
// which allows us to register a controller on the window object. 
$controllerProvider.register('ProductsController', function() { 
    // logic of the controller... 
}); 
}); 

回答

1

你混淆了两个不同的功能moduleinject

module配置茉莉环境中使用您指定的角模块。这可能是app。如果你不叫这个呢,喷油器将无法找到你的服务,控制器,指令等。在module功能,你可以注入providers,不服务,工厂等你用提供商配置如何这些服务将表现得更晚。

inject调用它之前需要您提供的功能和“内喷射”的服务,常量,工厂等的名字。你使用它来自己的服务等。

下面是如何分割在代码中调用一个样本。我还将$scope更改为使用$rootScope并创建一个范围。

beforeEach(function() { 
    module("app"); //or if your module is name something different, use that name instead 

    inject(function($controller, $rootScope) { 
     var $scope = $rootScope.$new(); 
     var myCtrl = $controller("myCtrl", { $scope: $scope }); 
    })); 
}); 
+0

在模块函数1中有3种传递参数的方法。字符串2.函数3.对象文字。 – user3045179

+0

@ user3045179三个人都做不同的事情。如果您使用字符串参数,则会找到具有该名称的模块。如果您使用某个功能,它将使用该功能*创建一个新模块*。如果您使用一个对象,它将为每个属性放入一个模块。您可以查看[文档](https://docs.angularjs.org/api/ngMock/function/angular.mock.module)以获取更多信息。 –

+0

你是对的,但是我认为当你使用模块时,它无法在提供者缓存中找到$ scope。 – user3045179