AngularJS ng-click服务和承诺

时间:2016-07-25 09:09:05

标签: javascript angularjs angular-promise

我一直是AngularJS的初学者,并且对...有知识问题 我想做的事情几乎很简单 - 视图中的按钮触发条形码扫描,扫描完成后,用扫描结果填充视图字段。

在视图中:

<button id="ajouter-button3" class=" button button-positive  button-block " ng-click="scanBarCode()">Scanner</button>

后来在视图中:

        <label class="item item-input " id="add-ean" name="ean">
            <span class="input-label">EAN</span>
            <input type="text" placeholder="Code EAN" name="add.ean" ng-model="add.ean" value="{{add.ean}}">
        </label>

放入控制器:

    .controller("ajouterCtrl", ["$scope", "$ionicPopup", "$timeout", "ScanDatas", "ScanService" , "storageAreaService", function ($scope, $ionicPopup, $timeout, ScanDatas, ScanService, storageAreaService) {
    "use strict";
    $scope.storageAreas = storageAreaService.storageAreaList();
    $scope.add = {}; // Initalise l'objet


    $scope.scanBarCode = function(){
        ScanService.getBarcodeData().then(function(datas){
            console.log("Retour de la méthode d'acquisition");
            $scope.add.ean = datas.text;
        })
    };

}])

services.js 中,想要在扫描完成后推迟获得承诺,但是。我不明白延迟/承诺/功能是如何协同工作的,我试过这个:

.factory("ScanService", ["$q", "ScanDatas","$cordovaBarcodeScanner", function ($q, ScanDatas, $cordovaBarcodeScanner) {
var scan = {};

var scanBarCode = function(){
    var readDatas = {};

    $cordovaBarcodeScanner.scan().then(function(datas){
        readDatas.text = datas.text;
        readDatas.format = datas.format;
        readDatas.cancelled = datas.cancelled;
        readDatas.processed = true;
    },function(error){
        readDatas.error = true;
    });

    return readDatas;
}

var getBarcodeData = function(){
    var deferred = $q.defer();

    deferred.resolve(scanBarCode());

    return deferred.promise;
};

return {
    getBarcodeData: getBarcodeData
}
}])

当我运行应用程序时... $scope.scanBarCode会立即触发日志,而我预计console.log仅在deferred.resolve 承诺之后触发。我不明白为什么会这样。

1 个答案:

答案 0 :(得分:0)

将此作为您的服务:

.factory("ScanService", ["$q", "ScanDatas","$cordovaBarcodeScanner", function ($q, ScanDatas, $cordovaBarcodeScanner) {
  var scan = {
    scanBarCode : function(){
      var deferred = $q.defer();
      var readDatas = {};
      $cordovaBarcodeScanner.scan().then(function(datas){
          readDatas.text = datas.text;
          readDatas.format = datas.format;
          readDatas.cancelled = datas.cancelled;
          readDatas.processed = true;
          deferred.resolve(readDatas);
      },function(error){
          readDatas.error = true;
      });

      return deferred.promise;
    }
  };

  return scan;
}]);

并从控制器中调用它:

$scope.scanBarCode = function(){
    ScanService.scanBarCode().then(function(datas){
        console.log("Retour de la méthode d'acquisition");
        $scope.add.ean = datas.text;
    })
};

谢谢!