angularjs中$scope和scope的区别 [英] Difference between $scope and scope in angularjs
问题描述
我是 angularjs 的新手.我想知道 angularjs Controller 中的 $scope
和 angularjs Directive 中的 scope
有什么区别.
I am new to angularjs. I would like to know what is the difference between $scope
in angularjs Controller and scope
in angularjs Directive.
我尝试在控制器中使用范围,但出现以下错误:
I tried to use scope in controller and I got the below error:
错误:[$injector:unpr] 未知提供者:scopeProvider <- scope
Error: [$injector:unpr] Unknown provider: scopeProvider <- scope
推荐答案
$scope
是由 $scopeProvider
提供的服务.您可以使用 Angular 的内置依赖注入器将其注入到控制器、指令或其他服务中:
$scope
is a service provided by $scopeProvider
. You can inject it into controllers, directives or other services using Angular's built-in dependency injector:
module.controller(function($scope) {...})
这是
module.controller(['$scope', function($scope) {...}])
在第一个版本中,依赖注入器根据函数参数的名称($scope"+Provider")推断提供者的名称($scopeProvider").第二个版本也像这样构建提供者名称,但使用数组中的 explicit '$scope'
,而不是函数参数名称.这意味着您可以使用任何参数名称而不是 $scope
.
In the first version the Dependency Injector infers the name of the provider ("$scopeProvider") based on the name of the function parameter ("$scope" + "Provider").
The second version also builds the provider name like that but uses the explicit '$scope'
in the array, not the function parameter name. That means you can use any parameter name instead of $scope
.
因此你最终得到这样的代码:module.controller(['$scope', function(scope) {...}])
其中 scope
可以是任何东西,它是一个函数参数名称,可以是 foo
或 a12342saa
.
Thus you end up with code like this:
module.controller(['$scope', function(scope) {...}])
where scope
could be anything, it's a function parameter name, could be foo
or a12342saa
.
依赖注入器基本上是这样做的:
The dependency injector basically does this:
function controller(def) {
//def[def.length-1] is the actual controller function
// everything before are it's dependencies
var dependencies = [];
for(dep in def.slice(0, def.length-1)) {
dependencies.push(__get_dependency_by_name(dep));
}
def[def.length-1].apply(dependencies);
}
我认为使用scope"而不是$scope"作为依赖名称的原因现在已经很清楚了.没有定义scopeProvider".
I think the reason why using "scope" instead of "$scope" as a dependency name won't work is clear now. There's no "scopeProvider" defined.
这篇关于angularjs中$scope和scope的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!