"Don't make functions within a loop." lint error. What is the correct way to write it?

52 Views Asked by At

The controller code is given below. What is the correct way to solve this?

$scope.photoData = [];
$cordovaImagePicker.getPictures(options).then(function (results) {
  for (var i = 0; i < results.length; i++) {
    $scope.photoData.push(results[i]);
    console.log(results[i]);
    window.plugins.Base64.encodeFile(photoData, function(base64) {
      console.log('photoData: ' + base64);
    });
  }


  if (!$scope.$$phase) {
    $scope.$apply();
  }
}, function (err) {
  // An error occured. Show a message to the user
});

view code

    <ion-slide ng-repeat="item in photoData">
    <img ng-src="data:image/jpg;base64,{{item}}" style="max-width: 100%">
  </ion-slide>
1

There are 1 best solutions below

2
Marc On

You can declare the function before the loop begins

$cordovaImagePicker.getPictures(options).then(function(results) {
    function successFunc(base64) {
        console.log('photoData: ' + base64);
    }

    for (var i = 0; i < results.length; i++) {
        $scope.photoData.push(results[i]);
        console.log(results[i]);
        window.plugins.Base64.encodeFile(photoData, successFunc);
    }
    if (!$scope.$$phase) {
        $scope.$apply();
    }
}, function(err) {
    // An error occured. Show a message to the user
});