How to call function from div on load in angularjs

I am trying to pull value in div element and once I get value I would like to call a function to get data. I am unable to call function inside div element HERe is my Html

stats.html

<div class="ItemsList" data-ng-init="GetStatsData({{menu.result}})">
 {{myitems}}
<div>

RootController.js

function GetStatsData(resultval) {
 homeService.getitemsData(resultval)
        .success(function (data, status, headers, config) {
                        $scope.myitems = data
                });
}

I am getting data when calling function directly but when I try to use div tag and invoke the function I cannot get this working, Its never calling that function. My main goal is to get value in myitems passing menu.result in function.

I appreciate any help to get this resolved

Answer

As mentioned in the documentation ngInit
The only appropriate use of ngInit is for aliasing special properties of ngRepeat

You should change the way you you call GetStatsData to be called from the controller as follow

$scope.group.menuData = []   // set the array of data here

for(n = 0, n <  $scope.group.menuData.length, n++) {
   // wrap you async calls inside function when in loop
   $(function(index) {
       //CALL GetStatsData
       GetStatsData($scope.group.menuData[index]);
   })(n);
}

The implementation of GetStatsData need little modification

function GetStatsData(menu) {
     homeService.getitemsData(menu.result)
    .success(function (data, status, headers, config) {
                    menu.myitems = data
            });
}

Now your view html should be like this

<div class="ItemsList">
  {{menu.myitems}}
 <div>

Leave a Reply

Your email address will not be published. Required fields are marked *