Search code examples
angularjsangularjs-directiveangularjs-scope

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


Solution

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