1

I use angularjs and I have a problem with ng-if when I use a function that returns true or false in two API, the browser is freezes

self.isShow= function() {
    service.getKioskLogByKioskId([stateParams.kioskId], function (data) {
        self.kioskLog = data;
        service.getKiosk([stateParams.kioskId], function (kiosk) {
            self.kiosk = kiosk;
            debugger 
            if (self.kioskLog.isConnected && self.kiosk.isActive)

                return true;
            else
                return false;

        });
    });
}

and in html

ng-if="self.isShow()"
georgeawg
  • 48,608
  • 13
  • 72
  • 95
milad dn
  • 43
  • 1
  • 1
  • 9
  • 1
    Why you have `debugger` statement? That will surely get your browser stuck in debug mode. – 31piy Jul 17 '18 at 04:54

1 Answers1

7

Angular's ng-if can't be an async, it expects to get true/false in synchronous manner.

Don't forget that EVERY angular directive creates a "watch" that will be invoked as part of angular's dirty check mechanism, If you make a "heavy" operation on it, it will stuck the browser.

Basically there are 2 wrong things in your code, the first one, your isShow is not returning boolean value at all, (it always returns undefined). The second one, you are probably making an API call inside the service.getKioskLogByKioskId method.

In order to solve both of the issues, you can make the service.getKioskLogByKioskId call inside the constructor of you controller, (if it is a component there is $onInit lifecycle hook for that), then save the async result on the controller, and use it the view.

It should look something like that:

class MyController {
  constructor(stateParams) {
    this.stateParams = stateParams;
    this.isShow = false; // initial value
  }

  $onInit() {
     const self =this;
     service.getKiosk([stateParams.kioskId], function (kiosk) {
          self.kiosk = kiosk;
          debugger 
          if (self.kioskLog.isConnected && self.kiosk.isActive)
              self.isShow = true;
          else
              self.isShow = false;

     });
  }
}


// view.html
<div ng-if="$ctrl.isShow"></div>
felixmosh
  • 32,615
  • 9
  • 69
  • 88