In Angularjs, is there a specific reason to use $scope in controllers and scope (without "$") in directives link function? Is it just a convention or anything else?
-
1It's just a variable name, so not really.ivarni– ivarni2013-10-10 06:33:46 +00:00Commented Oct 10, 2013 at 6:33
-
similar question heregarst– garst2013-10-10 07:37:02 +00:00Commented Oct 10, 2013 at 7:37
-
You can find also a very good video answer to this question by John Lindquist here: http://egghead.io/lessons/angularjs-scope-vs-scope.Adam Bogdan Boczek– Adam Bogdan Boczek2013-10-16 21:16:18 +00:00Commented Oct 16, 2013 at 21:16
5 Answers
The case when you do $scope in controller the Dependency Injection injects scope based on matching the variable name $scope, in this case using scope as name would not work.
For case of directive the injection is position based so you can name your variable a or b or any thing. The directive order for link function is
(scope, iElement, iAttrs, controller)
so first element is always scope object.
1 Comment
scope is really just convention." (I can't find any good explanation why $scope isn't used here, as well, if only for consistency)The module factory methods like controller, directive, factory, filter, service, animation, config and run receive arguments through dependency injection (DI). In case of DI, you inject the scope object with the dollar prefix i.e. $scope. The reason is the injected arguments must match to the names of inject-able objects followed by dollar ($) prefix.
For example, you can inject the scope and element objects into a controller as given below:
module.controller('MyController', function ($scope, $element) { // injected arguments });
When the methods like directive linker function don’t receive arguments through dependency injection, you just pass the scope object without using dollar prefix i.e. scope. The reason is the passing arguments are received by its caller.
module.directive('myDirective', function () // injected arguments here
{
return {
// linker function does not use dependency injection
link: function (scope, el, attrs) {
// the calling function will passes the three arguments to the linker: scope, element and attributes, in the same order
}
};
});
In short, in case of dependency injection the scope object is received as $scope while in case of non-dependency injection scope object is received as scope or with any name.
Comments
The $ in "$scope" indicates that the scope value is being injected into the current context.
$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) {...}])
However, scope could be anything, it's a function parameter name, could be foo or a12342saa.
function link( scope, element, attributes ) {
// Only scope
}