将服务调用从指令传递到 angularJS 中的控制器

问题描述

我有一个指令,接收一个文件上传到 httpPostFactory 服务和 PHP 代码

<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

    });
  };
});
工作正常,PHP 向 scope.variable 返回一个名称,但无法获取控制器中的值

所以,我试图将变量从指令传递给控制器​​(不成功)或从控制器调用服务,但未定义 formData

<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 文件一个简单的表单

          <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 文件仅供参考

<?PHP

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

// uploads image in the folder images
    $temp = explode(".",$_FILES["file"]["name"]);
    $newfilename = substr(md5(time()),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);
}
?>
关键是,我需要控制器中服务返回的变量。 顺便说一句,这是我设法将文件上传到服务器的唯一代码

解决方法

您可以尝试将 ur 指令中的 scope.formData 绑定到附加了文件的变量 formData

通过这种方式,您可以将指令中的数据传递给控制器​​,并从控制器进行服务调用。

<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);

      });
  
  }
  
  
  
}])