3

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
  • This link is useful for you Commented May 14, 2015 at 11:22

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks i am able to get the dependency injector's working but i would like to know about the isolated scope , why we are using an isolate scope in directives instead of $scope
An isolated scope is still a scope. Read the docs here: docs.angularjs.org/guide/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.