I've been using var and $scope.varname and both work fine in AngularJS. I was wondering if there was a difference between the two functionally, and what best practice was in which one to use?
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 $ 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.
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 .
Yes! $scope
variables bind to the view where as var
does not and is local to the function it was declared in!
var x = 3; $scope.y = 3; {{x}} - undefined {{y}} - 3
The technical implications of using var
and $scope
have been described by @tymeJV and others. I think the next logical question answer is: When do I use either?
TL;DR - if you do not use a variable in a view (e.g. {{myVar}}
), use var
.
The reason is two fold:
Encapsulation - hide state that is not necessary to the view. This will prevent unintended modifications of the variable.
Performance (prevent extra digest cycles) - Angular performs "dirty state" checking on variables. Modifying a variable that's not used in the view may cause extra digest cycles unnecessarily. In an application with a couple of ng-repeat
s and a bunch of watches, this can have a huge impact.
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