As a beginner in AngularJS, I am facing a knowledge gap when it comes to integrating a barcode scan feature into my application. What I want to achieve is quite simple - a button in the view that, when clicked, triggers a barcode scan. Once the scan is complete, I need the scanned result to populate certain fields in the view.
Here's the button in the view:
<button id="ajouter-button3" class=" button button-positive button-block " ng-click="scanBarCode()">Scan</button>
And later in the view:
<label class="item item-input " id="add-ean" name="ean">
<span class="input-label">EAN</span>
<input type="text" placeholder="EAN Code" name="add.ean" ng-model="add.ean" value="{{add.ean}}">
</label>
In the controller:
.controller("ajouterCtrl", ["$scope", "$ionicPopup", "$timeout", "ScanDatas", "ScanService" , "storageAreaService", function ($scope, $ionicPopup, $timeout, ScanDatas, ScanService, storageAreaService) {
"use strict";
$scope.storageAreas = storageAreaService.storageAreaList();
$scope.add = {}; // Initialize object
$scope.scanBarCode = function(){
ScanService.getBarcodeData().then(function(datas){
console.log("Returned from acquisition method");
$scope.add.ean = datas.text;
})
};
}])
Within the services.js file, I am attempting to use defer and promises once the scan is complete. However, I am struggling to understand how these concepts work together. My current implementation looks like this:
.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
}
}])
Upon running the app, I noticed that the log is fired immediately within $scope.scanBarCode
, whereas I expected it to only fire after deferred.resolve
promise. I am confused as to why this behavior is occurring.