首页 > 解决方案 > 在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()), 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);
}
?>
关键是,我需要控制器中服务返回的变量。顺便说一句,这是我设法将文件上传到服务器的唯一代码

标签: angularjsangularjs-directiveuploadangularjs-controller

解决方案


您可以尝试scope.formData在 ur 指令中绑定到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);

      });
  
  }
  
  
  
}])


推荐阅读