Skip to content Skip to sidebar Skip to footer

Execute A Function Inside Ng-repeat In Angularjs

I would like to execute a function inside a ng-repeat to retrieve some other data to show. For example I've a list of Apartments. I show this list using ng:repeat, than for each Ap

Solution 1:

You should create a custom directive pass in any data you want from the ng-repeat and do any action you want. The directive will fire its link function on every ng-repeat loop

var app = angular.module('myApp', [])
.controller('myCtrl', function($scope){
  
  $scope.data = ['a', 'b', 'c'];
  
})
.directive('myDirective', function(){
  return {
    restrict: "A",
    template: '<div>{{ myDirective }}</div>', // where myDirective binds to scope.myDirectivescope: {
      myDirective: '='
    },
    link: function(scope, element, attrs) {
      console.log('Do action with data', scope.myDirective);
    }
  };
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="myApp"><divng-controller="myCtrl"><ul><ling-repeat="item in data"my-directive="item">{{ item }}</li></ul></div></div>

Check your console for the action

Solution 2:

the reason why this error happens is :

getInq return $scope.nomeCognome, and $scope.nomeCognome change every time when ng-repeat iterate the collection, every change will trigger the $digest cycle, which will cause a horrible result. you should avoid something like this will make $digest much complicated.

Solution 3:

angular directives are used to manipulate the 2 way data binding, you should not call the methods, as you have shown specially from within the two ng-repeat they are basically loops, It would slow down your page loading also. you should properly create your JSON for data binding within the controller. below should be you HTML code:

<div ng:repeat="u in units">
            <div ng:repeat="a in u.Apartments">
                <div class="targhetta" style="margin-top:10px">{{a.Name}}/div>

                <table>
                    <tr ng:repeat="cs in a.CS">
                        <td>{{cs.Position}}</td>
                        <td>{{cs.Code}}</td>
                    </tr>
                </table>
            </div>
        </div>

and in controller you should create your JSON as

units=[
      { u.Appartment:[{a.cs[value1,value2]},{},{}]},{},{}]

something like this

for( var i=0; i<u.Apartment.length;i++)
{

  u.Apartment[i].cs=$scope.getInq(u.Apartment[i].Id);
}

Solution 4:

Do not use {{getInq(a.ApartmentId)}} in your html. It will generate an awful lot of http request, that is why you are getting an error.

Instead call this function for every item you need from your controller, and add to the $scope.units variable to the correct place. This will end up just enough http request, and once you have them, will stop running more.

Post a Comment for "Execute A Function Inside Ng-repeat In Angularjs"