Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$scope vs var in AngularJS

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?

like image 559
itamar Avatar asked Jun 18 '14 14:06

itamar


People also ask

What is $scope in AngularJS?

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

What is the difference between $scope and scope in AngularJS?

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.

What is difference between $scope and $rootScope object?

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.

Is $scope still supported in angular2?

In Angular 2.0, there will be no $scope .


2 Answers

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 
like image 185
tymeJV Avatar answered Oct 01 '22 01:10

tymeJV


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:

  1. Encapsulation - hide state that is not necessary to the view. This will prevent unintended modifications of the variable.

  2. 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-repeats and a bunch of watches, this can have a huge impact.

like image 26
Richard Clayton Avatar answered Oct 01 '22 02:10

Richard Clayton