2016-07-25 93 views
0

我總是在AngularJS初學者和有知識的問題... ,我想要做的幾乎是簡單:AngularJS NG-點擊服務,並承諾

在視圖按鈕觸發條形碼掃描和一旦掃描完成後,填充視野與掃描的結果...

我下面......

在視圖:

<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,要推遲到得到一個承諾掃描完成後,但... (「ScanService」,[「$ q」,「ScanDatas」,「$ cordovaBarcodeScanner」,函數($ q,ScanDatas),我不明白延遲/承諾/函數是如何協同工作的,請試試這個:

.factory ,$ 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承諾之後激發的。不明白爲什麼這種行爲解僱。 ..

JL

回答

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

謝謝!

+0

嘗試這種方法,但是當我運行時,得到: ionic.bundle.js:25642錯誤:[$ injector:undef] Provider'ScanService'必須從$ get factory方法返回一個值。 想想我錯過了什麼 –

+0

只需添加返回掃描以解決以前... –

+0

修復它的代碼... – kukkuz