Reputation: 6626
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?
Upvotes: 37
Views: 21267
Reputation: 41
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.
Upvotes: 2
Reputation: 159
The "$" in "$scope" indicates that the scope value is being injected into the current context. But, not all references to scope are based on dependency injection.
Upvotes: 0
Reputation:
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
}
Upvotes: 1
Reputation: 554
The reason of this behavior is that, Unlike controllers, directives don't use dependency injection, instead they are passed the scope created by the controller that is placed behind the view. this is very tricky, So you can reuse your directive on different scopes.
Upvotes: 1
Reputation: 42669
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.
Upvotes: 29