Passing service call from directive to controller in angularJS

56 Views Asked by At

I have a directive, who receive a file to upload in httpPostFactory service and php code

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
app.directive('myFile', function(httpPostFactory) {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {

      element.bind('change', function() {
        var formData = new FormData();
        formData.append('file', element[0].files[0]);
         
        scope.$apply();

        // Service Call
        httpPostFactory('php/global/post.upload.php', formData, function (value) {
               // nombre    
            scope.variable = value;
            console.log(scope.variable);

        });
        
      });

    }

  };
});

app.factory('httpPostFactory', function($http) {
  return function(file, data, callback) {
    $http({
      url: file,
      method: "POST",
      data: data,
      headers: {
        'Content-Type': undefined
      }
    }).success(function(response) {
      callback(response); // VARIABLE OK

    });
  };
});
Works fine, PHP return a new name to scope.variable but can't take the value in the controller

So, i'm trying to pass the variable from directive to controller (unsuccessfully) or calling the service from the controller, but the formData is not defined

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
app.controller('perfilEmpleadoCtrl', ['$scope','$http', '$routeParams' , 'httpPostFactory',
    function ($scope, $http, $routeParams, httpPostFactory) {
    
  // CALL SERVICE HERE - formData not defined obviously 
  
}])

HTML File is a simple form

          <form name="frmCurso"
                ng-submit="getImportar()"
                novalidate="novalidate">

<div class="form-group" ng-show="cuentaSel.status_det == 'FINALIZADO'">
                  <label for="exampleInputFile">Archivo de certificación</label>
                  <input data-my-File type="file" name="file">
                  
                  <p class="help-block">Soporta archivos de imagen hasta 2MB</p>
                  <div ng-bind="variable"></div>
            </div>
                
          </div>
          
            <div class="modal-footer">
              <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Guardar</button>
            </div>
      </form>

PHP File fyi

<?php

if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {

// uploads image in the folder images
    $temp = explode(".", $_FILES["file"]["name"]);
    $newfilename = substr(md5(time()), 0, 10) . '.' . end($temp);
    move_uploaded_file($_FILES['file']['tmp_name'], __DIR__.'../../../upload/'. $newfilename);

// give callback to your angular code with the image src name
    echo json_encode($newfilename);
}
?>
The point is, i need the variable returned by the service in the controller. Btw, it's the only code that I have managed to upload files to the server

1

There are 1 best solutions below

3
joohong89 On

You can try binding scope.formData in ur directive to the variable formData that has file appended.

This way, u can pass data from your directive to your controller and make a service call from your controller.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>

/*Added scope*/
app.directive('myFile', function(httpPostFactory) {
  return {
    restrict: 'A',
    scope: {
      formData: '='
    },
    link: function(scope, element, attrs) {

      element.bind('change', function() {
        var formData = new FormData();
        formData.append('file', element[0].files[0]);
         
        scope.$apply();
        
        scope.formData = formData;
        
        // Removed Service Call

        
      });

    }

  };
});

app.factory('httpPostFactory', function($http) {
  return function(file, data, callback) {
    $http({
      url: file,
      method: "POST",
      data: data,
      headers: {
        'Content-Type': undefined
      }
    }).success(function(response) {
      callback(response); // VARIABLE OK

    });
  };
});

<form name="frmCurso"
                ng-submit="getImportar()"
                novalidate="novalidate">

<div class="form-group" ng-show="cuentaSel.status_det == 'FINALIZADO'">
                  <label for="exampleInputFile">Archivo de certificación</label>
                 <!-- <input data-my-File type="file" name="file"> -->
                  <!-- directive name here should be my-file ? -->
                  <input my-file form-data="controllerFormData" type="file" name="file">
                  
                  <p class="help-block">Soporta archivos de imagen hasta 2MB</p>
                  <div ng-bind="variable"></div>
            </div>
                
          </div>
          
            <div class="modal-footer">
              <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Guardar</button>
            </div>
      </form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.3/angular.min.js"></script>
app.controller('perfilEmpleadoCtrl', ['$scope','$http', '$routeParams' , 'httpPostFactory',
    function ($scope, $http, $routeParams, httpPostFactory) {
  
  //declare scope variable
  $scope.controllerFormData = '';
  $scope.variable = '';
  


  
  $scope.someAction = function() {
  
      // CALL SERVICE HERE - formData should be passed via  $scope.controllerFormData
      httpPostFactory('php/global/post.upload.php', $scope.controllerFormData, function (value) {
          $scope.variable = value;
          console.log($scope.variable);

      });
  
  }
  
  
  
}])