Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $scope and scope in angularjs

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

like image 895
Avinash Solanki Avatar asked May 01 '26 03:05

Avinash Solanki


1 Answers

$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.

like image 132
Sergiu Paraschiv Avatar answered May 02 '26 17:05

Sergiu Paraschiv