1

I am calling a controller function in ng-if as below, But checkUserExamEnrollment function is getting called repeatedly. Can anyone suggest what's wrong in the code ?

View:

<div ng-if="checkUserExamEnrollment()== 0">Sample Data here if ng-if true</div>

Controller:

$scope.checkUserExamEnrollment = function()
    {
        var url = "http://localhost/api/examnew";

        return $http.get(url);
    }
Pinal Dave
  • 533
  • 4
  • 14
  • 27
  • Is it inside a `ng-repeat`? – developer033 Jul 05 '16 at 13:11
  • no, it's not inside ng-repeat – Pinal Dave Jul 05 '16 at 13:12
  • 6
    Yes, `ng-if` will evaluate its expression when digest cycle runs(multiple times), basically you shouldn't make an ajax call from `ng-if` expression – Pankaj Parkar Jul 05 '16 at 13:13
  • 5
    This is a major design flaw. First off your function doesn't return anything so condition will never be met. Next you should understand how digest cycles work and should never be making `$http` requests from such a function in view. What are you trying to do? – charlietfl Jul 05 '16 at 13:16

2 Answers2

6

Your ng-if will be called on every digest loop. The problem is that it contains an expression involving a function call. Angular has no way to know when the result of the expression might change, so it calls it every time.

When a $digest cycle runs, the watchers are executed to see if the scope models have changed. If they have, then the corresponding listener functions are called. This leads to an important question. What if a listener function itself changed a scope model? How would AngularJS account for that change?

The answer is that the $digest loop doesn’t run just once. At the end of the current loop, it starts all over again to check if any of the models have changed. This is basically dirty checking, and is done to account for any model changes that might have been done by listener functions. So, the $digest cycle keeps looping until there are no more model changes, or it hits the max loop count of 10.

Himanshu Mittal
  • 794
  • 6
  • 19
0

If your http call return an object or an array, then you can just store it in a Scope variable (eg: $scope.result) and use:

    <div ng-if="result">Sample Data here if ng-if true</div>

This will check the contents of $scope.result and show it only if it is not null.

Hope this helps

David H.
  • 507
  • 2
  • 10