22

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

FarazShuja
  • 2,287
  • 2
  • 23
  • 34

2 Answers2

51

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>
Praveen Srinivasan
  • 1,562
  • 4
  • 25
  • 52
Dinesh ML
  • 921
  • 11
  • 15
  • I have similar situation but I have to call the method when ng-if's value is false. Is there a way? @Dinesh ML – Rahul Pandey Mar 01 '17 at 05:16
  • 1
    @RahulPandey , you can try to call the same condition in the same way only add a '!' before: for example ng-if="i.name != 'abc'" or ng-if="!(i.name == 'abc)'" – Li3ro Apr 04 '17 at 07:15
0

if you want to call function when condition is true or false, you can try this:

<md-card
        class="ew-service-card"
        ng-click="campaign.status == 'completed' ? $ctrl.newServiceCard() : $ctrl.newServiceCardDisable()">
 </md-card>
Rizwan
  • 3,741
  • 2
  • 25
  • 22