Search code examples
javascriptangularjsangularjs-ng-repeatangularjs-ng-show

Executing function in ng-repeat give error


I have to run a function during a ng-repeat like this

<tr ng-repeat="x in listaService track by $index">
   <td>{{x.label}}</td>
   <td><span ng-show="showNoRole(x.label)" id="bannerRole">Nessun Ruolo</span> </td>
</tr>

and in the angular controller I have this function for control the ng-show:

$scope.showNoRole = function(label) {
   RicercaRuoloService.load(label).then(function(data) {

      if (data != "\"null\"") {
         return false;
      } else {
         return true;

      }
   }, function(error) {
      $scope.ErroreConnessione = true;
   })
}

the function RicercaRuoloServicereturns an array or "\"null\""if the array is empty. The problem is when I go to the page where is the ng-repeat the console start to print as loop this error:

angular.min.js:107 Error: [$rootScope:infdig] http://errors.angularjs.org/1.4.8/$rootScope/infdig?p0=10&p1=%5B%5D
    at angular.min.js:6
    at r.$digest (angular.min.js:131)
    at r.$apply (angular.min.js:134)
    at g (angular.min.js:87)
    at T (angular.min.js:92)
    at XMLHttpRequest.w.onload (angular.min.js:93)

and the cpu usage go frof 20% to 100% until I close the page. How can I fix this problem? Best reguards

EDIT: this is the array from listaService:

[{"_id":"test","label":"test","descrizione":"descrizione test","url":"http://www.virgilio.it","tipoProfilo":"NGPFNL","periodoValidazione":370,"direct":false,"preValid":false,"deleted":false},{"_id":"test2","label":"test2","descrizione":"descr test2","url":"http://www.google.com","tipoProfilo":"NGPFNL","periodoValidazione":123,"direct":false,"preValid":false,"deleted":false}]

EDIT2: RicercaRuoloService is just an Angular service that call a rest service and take data form db. The rest service works great 'couse I used it for other page too but never as a function in a ng-repeat.


Solution

  • Try one time binding. Right now your function is executed in every digest cycle of angularJS.

    ng-show="::showNoRole(x.label)"
    

    Also try

    $scope.showNoRole = function(label) {
    var result;
    RicercaRuoloService.load(label).then(function(data) {
    
        if (data != "\"null\"") {
            result = false;
        } else {
            result = true;
        }
    }, function(error) {
        result = false;
        $scope.ErroreConnessione = true;
    })
    return result;
    }