Difference between $scope and scope in angularjs

旧街凉风 提交于 2019-12-09 19:15:31

问题


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:

Error: [$injector:unpr] Unknown provider: scopeProvider <- scope


回答1:


$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) {...})

which is shorthand for

module.controller(['$scope', function($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.

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);
}

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.



来源:https://stackoverflow.com/questions/30234637/difference-between-scope-and-scope-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!