javascript - 通过在 angularjs 中单击按钮发送要由服务器安装的文件名称

标签 javascript angularjs angularjs-scope

我的网页显示服务器上的文件列表,文件名旁边有一个“安装”按钮。当我单击“安装”时,服务器应该收到要安装的相应文件的名称。我当前的代码无法将文件名称 psas 发送到服务器。您能否建议如何在单击按钮时将文件名发送到服务器?

这是我的代码

app.controller('RdaController', ['$scope', 'RdaService',
  function($scope, RdaService) {
    $scope.greeting = "Hello world";

    $scope.file = "installJob.zip";
    $scope.sendToCTP = function($scope) {
      return RdaService.SendFileToCTP($scope);
    };
  }
]);


app.service('RdaService', ['$http',
  function($http) {
    this.SendFileToCTP = function($scope) {
      return $http({
        method: "GET",
        url: "../api/CTP/installJobFromFile/" + $scope.file,
        headers: {
          'Content-Type': 'application/json'
        }
      }).success(function(data) {
        //$scope.sendToCTP = data;
        console.log(data);
      }).error(function(data) {
        console.log(data);
      });
    };
  }
]);
<h2>List of Files available</h2>
<table class="table table-striped">
  <tr ng-repeat="file in listOfFiles">
    <td>{{ file }}</td>
    <td><span class="btn-group" role="group"><button type="button" class="btn btn-default" ng-click="sendToCTP(file)">install</button><button type="button" class="btn btn-default">delete</button></span>
    </td>
  </tr>
</table>

最佳答案

您不应将 $scope 传递给服务。不过,您可以直接传递文件名。试试这个:

app.controller('RdaController', ['$scope', 'RdaService',
  function($scope, RdaService) {
    $scope.greeting = "Hello world";

    $scope.file = "installJob.zip";
    $scope.sendToCTP = function(file) {
      return RdaService.SendFileToCTP(file);
    };
  }
]);


app.service('RdaService', ['$http',
  function($http) {
    this.SendFileToCTP = function(file) {
      return $http({
        method: "GET",
        url: "../api/CTP/installJobFromFile/" + file,
        headers: {
          'Content-Type': 'application/json'
        }
      }).success(function(data) {

        console.log(data);
      }).error(function(data) {
        console.log(data);
      });
    };
  }
]);

您的 HTML 看起来可以正常使用。如果您需要在 $http 返回后执行任何操作,可以使用 RdaService.SendFileToCTP 调用上的 .then() 来执行此操作。

关于javascript - 通过在 angularjs 中单击按钮发送要由服务器安装的文件名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461787/

相关文章:

javascript string regex替换引号之间的字符串

javascript - 如何获取嵌套数组中所有非嵌套项的长度?

javascript - Angular : How to run JavaScript from inside Directive after directive is compiled and linked

javascript - Firebase 事务不会更新 Firebase 数据库中的实际值

angularjs - 在表格 Angular 中正确显示 JSON

node.js - 在 $HTTP.post 之后更新 $scope

javascript - 如何在 angular($window).bind() 中访问它?

javascript - 仅捕获链接上的左键单击

javascript - 当第二个函数完成时,使用 Promise 在函数导出中返回一个值

javascript - Angular 中 .success() 或 .then() 哪个更好