AngularJS中$scope和scope的区别

3

我是新手使用angularjs。我想知道angularjs控制器中的$scope和angularjs指令中的scope之间有什么区别。

我试图在控制器中使用scope,但是我得到了以下错误:

错误: [$injector:unpr] 未知提供者: scopeProvider <- scope


这个链接对你很有用。 - Gunaseelan
1个回答

4

$scope是由$scopeProvider提供的服务。您可以使用Angular内置的依赖注入器将其注入到控制器、指令或其他服务中:

module.controller(function($scope) {...})

这是一种简写形式

module.controller(['$scope', function($scope) {...}])

在第一个版本中,依赖注入器根据函数参数的名称("$scope" + "Provider")推断提供程序的名称("$scopeProvider")。 第二个版本也是这样构建提供程序名称的,但在数组中使用了显式'$scope',而不是函数参数名。这意味着您可以使用任何参数名代替$scope

因此,您最终会得到像这样的代码: module.controller(['$scope',function(scope) {...}]) 其中scope可以是任何东西,它是函数参数名,可以是fooa12342saa

依赖注入器基本上执行以下操作:

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"。


谢谢,我已经成功使用依赖注入器了,但我想了解隔离作用域,为什么我们在指令中使用隔离作用域而不是 $scope。 - Avinash Solanki
隔离作用域仍然是一个作用域。在此处阅读文档:https://docs.angularjs.org/guide/directive#isolating-the-scope-of-a-directive - Sergiu Paraschiv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接