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?
The $scope in an AngularJS is a built-in object, which contains application data and methods. You can create properties to a $scope object inside a controller function and assign a value or function to it. The $scope is glue between a controller and view (HTML).
The main difference is the availability of the property assigned with the object. A property assigned with $scope cannot be used outside the controller in which it is defined whereas a property assigned with $rootScope can be used anywhere.
In Angular 2.0, there will be no $scope .
AngularJS Scope The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller.
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.
You can find also a very good video answer to this question by John Lindquist here: http://egghead.io/lessons/angularjs-scope-vs-scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With