Scopes in AngularJS define where every variable is visible and where it’s not. Scopes are hierarchical, where every parent scope is visible in the child scope but not the other way around.

$rootscope is the highest scope that is seen by all the controllers. Be careful when setting $rootscope variables. They’ll always be there until the app is completely closed, so avoid using $rootscope if possible.

$scope is the controller scope. Variables in this scope will be visible only in this controller and the HTMLs associated with it. Unlike the $rootscope variables, $scope variables will be initialized every time the controller is visited.

Let’s look at these case studies to understand scopes better.

ng-if vs ng-show

At first ng-if and ng-show look the same. But they’re not. The difference between them is the scope. Let’s look at this example:

	<div ng-show="items.length>0">
	     <button ng-click="gotIt ='yes'; show();">click here</button>
	</div>

Let’s define an array in the controller $scope.items and a function $scope.show that looks like:

	$scope.show = function(){
	      alert($scope.gotIt);
	};

Assume $scope.items has more than one element and the button is visible. When the user clicks the button an alert shows up that says “yes”. The logic is simple. We defined a variable called ‘gotIt’ and we accessed that variable from the controller. Now let’s replace ng-show with ng-if and click the button again. The alert now shows “undefined”. Why? Because ng-if creates a child scope that’s not accessible from the parent scope. Every variable defined in it is undefined to the parent. On the other hand, ng-show uses the same scope and the variable was visible.

ng-repeat

Let’s assume we have the same $scope.items array and we need to loop through it in the HTML:

	<div ng-repeat="item in items" >
	     <button ng-click="hideText=true; ">Hide Text</button>
	     <p ng-if="!hideText">Some Text</p>
	</div>

Every item in the list has a text and a button, and all of them use the same variable name “hideText”. When you click on any button, only the text associated with that button is hidden. The explanation is that ng-repeat creates a child scope for every item. So the “hideText” variable in one item is in a completely different scope than other “hideText” variables.

Share This