Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling a method only if ng-if is true

Tags:

Is it possible to call a method only when a condition in ng-if is true? I have a repeat like this

<div ng-repeat="i in items" ng-if="i.loc == 'abc'">     <h1>Hello.. {{getName()}}</h1> </div> 

here is the js code

$scope.getName = function() {     console.log('fired');     return "myName"; } 

From console I can see that this method is firing many more times then items.length and i.loc condition. So how to call this inside method only when ng-if is true

like image 724
FarazShuja Avatar asked May 22 '14 06:05

FarazShuja


People also ask

Can we call method in ngIf?

Calling a method will result in multiple calls, every time change detection occurs. In one of my apps, it called the method over 4,000 times, before resolving: medium.com/showpad-engineering/…

What is the use of NG-if?

Definition and Usage The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

Can we use ngIf and Ng show together?

ng-if is better in this regard. Using it in place of ng-show will prevent the heavy content from being rendered in the first place if the expression is false. However, its strength is also its weakness, because if the user hides the chart and then shows it again, the content is rendered from scratch each time.


Video Answer


1 Answers

If the condition is true , someMethod() will be called. For example,

<div ng-repeat="i in items"       ng-if="i.name == 'abc'"       ng-init="someMethod()"> </div> 
like image 130
Dinesh ML Avatar answered Oct 10 '22 18:10

Dinesh ML