Search code examples
javascriptangularjsangularjs-ng-showangularjs-ng-if

Multiple ng-if on the same condition - performance wise


I have a html page with different element, that according to some condition (the same condition) will be shown/hidden using Angular's ng-if.

In my controller, I create a boolean variable.

$scope.myCondition = getValue();

In my view, I listen to this variable using ng-if directive.

What will be better performance wise:

  1. Write cleaner code BUT with multiple ng-if on this condition:

<div>		
	<div ng-if="myCondition" >-- a --</div>
	<div ng-if="!myCondition">-- A --</div>	
	<div>
		-- text, text, text... --
	</div>
	<div ng-if="myCondition" >-- b --</div>
	<div ng-if="!myCondition">-- B --</div>	
	<div>
		-- text, text, text... --
	</div>
	<div ng-if="myCondition" >-- c --</div>
	<div ng-if="!myCondition">-- C --</div>	
	<div>
		-- text, text, text... --
	</div>
</div>

  1. Write code duplication (in the view) BUT use single ng-if:

 <div ng-if="myCondition">		
    	<div>-- a --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    	<div>-- b --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    	<div  >-- c --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    </div>
    <div ng-if="!myCondition">		
    	<div>-- A --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    	<div>-- B --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    	<div  >-- C --</div>
    	<div>
    		-- text, text, text... --
    	</div>
    </div>

I will prefer writing code as displayed in example No.1, since it is more maintainable. But I concerned that this way a new $watch will be created for each ng-if.
Is that correct? does Angular create new $watch for each ng-if, although this is the same static condition (not return value of some function but a simple variable).

This question asked regarding the ng-if directive but relevant also to ng-show and ng-hide


Solution

  • You're right, you will create a watcher for every used ng-if, so in terms of performance is better to use the second option.

    However, if your condition is going to be evaluated only once (when the controller executes its code) you can use the one-time-binding operator :: with ng-if to avoid $watchers.