Exploring the power of AngularJS with ng-click functionality and utilizing services

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.

Answer №1

Utilize the following code for your service:

.factory("BarcodeService", ["$q", "BarcodeData","$cordovaBarcodeScanner", function ($q, BarcodeData, $cordovaBarcodeScanner) {
  var barcode = {
    scanBarCode : function(){
      var deferred = $q.defer();
      var scannedData = {};
      $cordovaBarcodeScanner.scan().then(function(data){
          scannedData.text = data.text;
          scannedData.format = data.format;
          scannedData.cancelled = data.cancelled;
          scannedData.processed = true;
          deferred.resolve(scannedData);
      },function(error){
          scannedData.error = true;
      });

      return deferred.promise;
    }
  };

  return barcode;
}]);

To call this service from a controller, use the following code:

$scope.scanBarCode = function(){
    BarcodeService.scanBarCode().then(function(data){
        console.log("Returning from acquisition method");
        $scope.add.ean = data.text;
    })
};

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with caching: Browser cache not being utilized even after implementing Cache-Control Header

First Requesthttps://i.sstatic.net/xtJCW.png Second Inquiryhttps://i.sstatic.net/4R9ln.png I have implemented a node module(express-cache-ctrl) to activate caching on a proxy. app.use(cache.public(3600)); Despite having Cache-control headers with max-age ...

Eliminate the border and style of a link that was clicked before in a React/Next.js

I've created a function where clicking on an element adds borders using onClick trigger. Here's the code snippet from the component: import { useEffect, useState } from 'react'; import Link from 'next/link'; import Logo from ...

What is the reason behind Google Closure Compiler appending a variable to the global namespace when the original namespace was blank?

My long script is neatly enclosed within a (function() {/.../})() to prevent any name pollution. It has been typed with complete accuracy and zero warnings. I recently discovered that Google Closure compiler initially redefines i and j in the global names ...

Stripping HTML elements from the body of an HTML document using AJAX before transmitting it as data to the controller

My JSP page contains two buttons labeled "download" and "sendemail". When the "Sendmail" button is clicked, an ajax method is triggered to generate a PDF version of the HTML body and send it to the back-end controller. I attempted to utilize the following ...

Experiencing a 404 error with angular.js while working on a MEAN application with gulp

I'm facing an issue while setting up a new MEAN app using gulp and bower. Whenever I launch my app, I keep encountering 404 errors for my bower dependencies. I utilized express-generator to create the folder structure, but my intention was to leverage ...

What are the pros and cons of using a piped connection for Puppeteer instead of a websocket?

When it comes to connecting Puppeteer to the browser, you have two options: using a websocket (default) or a pipe. puppeteer.launch({ pipe: true }); What distinguishes these approaches? What are the benefits and drawbacks of each method? How do I know wh ...

Tips for incorporating JavaScript into elements that have been modified using jQuery's .html() method

Consider this example: $('#key').on('click', function(){ $('.task').html("<button id='key'>Button</button>"+Date()); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.j ...

Vue template is not being rendered when served through Django

I am currently working on a Django application where Vue is used as the frontend to render templates. In my Django view code, I have the following components: # thing/views.py def index(request): template = loader.get_template('thing/index.html&a ...

Exploring JS Pattern Matching across Two Distinct Data Sources

In my database, I have two tables (and more can be added in the future) with rows structured like this: <table> <tr> <th>name</th> <th>salary</th> </tr> <tr> <td>a</td> &l ...

Samsung browser encounters an international error

After developing my web application using Angular2 Rc1, I noticed that it functions perfectly on Safari, Firefox, and Chrome browsers. However, when trying to access the application on my Galaxy S6 using the default browser, an error pops up: To address ...

Shortcuts for $scope variables in AngularJS templates

Within my controller, I often set: $scope.currentThing.data For different parts of my template, sometimes I require currentThing.data.response[0].hello and other times currentThing.data.otherStuff[0].goodbye //or currentThing.data.anotherThing[0].goo ...

"Experience the power of Angular.js through seamless animations created by blending the capabilities

I want to smoothly fade out the old view and fade in the new view. The challenge is that the new content must be positioned absolutely until the old one fades out. I also want to set a specific top position and height for the new content, but when I try to ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Resolve Redux-Firestore issue #45: Possible Solutions?

I'm facing an issue where deleting a document from Firestore results in my Redux store showing it as null instead of removing it. Even though the document is deleted in Firestore, this inconsistency causes frontend issues because my .map functions can ...

Toggle a jQuery bar based on the presence of a specific CSS class

I am working on a feature where I can select and deselect images by clicking on a delete button. When an image is selected, a bar appears at the top. If I click the same delete button again, the image should be deselected and the bar should disappear. This ...

An intuitive approach to adding a CheckBox control within a GridView using JavaScript and SPAN elements

Struggling to calculate the total quantity from the gridview for checked row checkboxes? Having trouble accessing the checkbox control in your JavaScript? Below is the code snippet you provided, but it's not returning anything. <table cellspaci ...

"Utilizing datatables to efficiently submit form data to the server-side

I'm curious for those who utilize the Datatables javascript plugin, is there a way to replicate this specific example using server-side data? The current example I came across has its data hardcoded directly in the HTML. ...

Moving a div with arrow keys using percentages: A step-by-step guide

I found this amazing script on Stack Overflow that allows me to move elements around the page using arrow keys. It works flawlessly, and I love how it enables diagonal movement by combining different arrow key inputs. Now, my query is whether it's fe ...

Is Fullpage.js functioning only on local servers?

I have decided to create a personal website showcasing my portfolio using the fullpage.js library. Everything seems to be working fine during development, but once I upload the site to my github.io or another public domain via FTP, I encounter GET errors t ...

What are the typical situations in which Node.js is commonly used?

Do you believe that a majority of node.js users primarily utilize npm? What do you think are the most prevalent use cases for node.js apart from npm? ...