Moving the logical aspects to services (factory) with AngularJS: Enhancing the efficiency of your controllers

As a newcomer to Angular, I am facing some initial challenges. I have created a small app with phonegap, onsen ui, and angularjs that utilizes the nfc-plugin. My goal is simple - to read a tag-id from an nfc-tag. Everything works perfectly when I include all my code within the controller.

Here is what it looks like:

app.controller('Page3Ctrl', function($scope, Data) {
        $scope.item = Data.selectedItem.title;

        

        $scope.save = function() {
            Data.selectedItem.title = $scope.item;
            $scope.ons.navigator.popPage();
        };

        
        // Get the ID Number from the tag

        $scope.onNfc = function(nfcEvent) {
            
            var tag = nfcEvent.tag;
            var taglesen = nfc.bytesToHexString(tag.id);
            
            $scope.$apply(function() {
                $scope.item = taglesen;
            });
        };

        nfc.addTagDiscoveredListener(
             $scope.onNfc,             // tag successfully scanned --> call $scope.onNfc
             function (status) {    // listener successfully initialized
                $scope.nfcok = "NFC Reader ist ready";
             },
             function (error) {     // listener fails to initialize
                $scope.nfcok = "NFC Reader ist nicht ready";
             }
        );
    });
<ons-page class="center">
    <div ng-controller="Page3Ctrl">
        <ons-text-input ng-model="item" style="margin:10px;"></ons-text-input><br>
        <ons-text-input ng-model="nfcok" style="margin:10px;"></ons-text-input><br>
        <ons-button ng-click="save()">Save</ons-button>
        <ons-button ng-click="onNfc()">Scan NFC</ons-button>
    </div>
</ons-page>

Now, I want to move the NFC-reading functionality to a separate file called services.js and incorporate it into a factory. However, I am facing challenges in doing so.

I attempted the following approach, but unfortunately, it did not work. I may need some guidance or perhaps I am approaching this in the wrong way:

myApp.factory('onNfc', function() {
    
    this.getNfc = function(nfcEvent) {
      var tag = nfcEvent.tag;
      var taglesen = nfc.bytesToHexString(tag.id);
      return taglesen;
   }

   nfc.addTagDiscoveredListener(
             this.getNfc(),             // tag successfully scanned
             function (status) {    // listener successfully initialized
                $scope.nfcok = "NFC Reader ist ready";
             },
             function (error) {     // listener fails to initialize
                $scope.nfcok = "NFC Reader ist nicht ready";
             }
    );
});

app.controller('Page3Ctrl', function($scope, Data, onNfc) {
        $scope.item = Data.selectedItem.title;

        

        $scope.save = function() {
            Data.selectedItem.title = $scope.item;
            $scope.ons.navigator.popPage();
        };

                $scope.$apply(function() {
                $scope.item = onNfc.getNfc();
        });

        

        
    });

I appreciate any assistance provided.

Warm regards,

Answer №1

If you're looking to connect different modules within your service, one approach is to create an API that can be accessed by other components. For example:

myApp.factory('onNfc', function() {

    // Expose functions to other modules
    return {
       getNfc: getNfc
    };

    function getNfc(nfcEvent) {
      var tag = nfcEvent.tag;
      var tagRead = nfc.bytesToHexString(tag.id);
      return tagRead;
    }

    nfc.addTagDiscoveredListener(
         getNfc(),             // handle scanned tag
         function (status) {    // success callback
            $scope.nfcok = "NFC Reader is ready";
         },
         function (error) {     // error callback
            $scope.nfcok = "NFC Reader is not ready";
         }
    );
});

Answer №2

Big thanks to Gandalf for the helpful solution provided! I successfully implemented the procedure described above and even tested it with another function. However, I encountered a new issue with the following two lines of code.

 let tag = nfcEvent.tag;
let tagID = nfc.bytesToHexString(tag.id);

Although the nfc.addTagDiscoveredListener function is working correctly and triggering the getNfc function, it seems like there may be a problem with the "nfcEvent" variable. Should I be considering something else in relation to this issue? I have read about $rootScope but not sure if it applies here.

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

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...

myObject loop not functioning properly in Internet Explorer version 10

Could someone please point out what is wrong with this code snippet? HTML: <div id="res"></div> Javascript: var myObject = { "a" : { src : "someimagepath_a.png" }, "b" : { src : "someimagepath_b.png" }, }; va ...

Facebook has broadened the scope of permissions for canvas applications

I am in the process of developing a Facebook canvas application that requires extended permissions for managing images (creating galleries and uploading images) as well as posting to a user's news feed. I am currently facing challenges with obtaining ...

Encountering a proxy error while attempting to create an account or log in, with no network

Embarking on my first web development journey, I utilized React-Redux to craft a React.js application within the client folder. For the backend code, I employed Node.js and MongoDb as my database. This project represents a significant milestone in my lear ...

Deleting a property once the page has finished loading

My issue is a bit tricky to describe, but essentially I have noticed a CSS attribute being added to my div tag that seems to come from a node module. The problem is, I can't seem to find where this attribute is coming from in my files. This attribute ...

Display an error notification when the user fails to provide the necessary quantity of numbers in AngularJS

Hey there, I'm currently diving into the world of AngularJS development and facing some challenges with form validations. I have an input field that should only accept a maximum of 8 digits. My goal is to display an error message if less than or more ...

Creating an interactive dropdown feature using AngularJS or Ionic framework

$scope.AllCities = window.localStorage.getItem['all_cities']; <div class="row"> <div class="col"> <div class="select-child" ng-options="citie.name for citie in AllCities" ng-model="data.city"> <label&g ...

Setting a single value for several identifiers within a JSON object

I'm new to JSON and I'm curious if it's possible to have a name/value pair with multiple names. Essentially, I want to be able to search for either name and retrieve the same value without having to update the value in two different places. ...

There seems to be a hiccup in the system as we are unable

Upon visiting the URL address http://localhost:3000/test, I intend to load a log message. However, an error is returned stating "Cannot GET /test". Below is the code snippet in question: import express from 'express'; import React from 'rea ...

Receive notifications when there are modifications in the JSON data using AJAX and jQuery

Below is the code snippet I created: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sample JSON Data Update</title> </head> <body> <style> span { font ...

selecting unique elements using classes is not possible with jquery

I am experimenting with using ajax on dynamically generated html elements from django. I have tried selecting the instances by class, but for some reason, it is not working as expected. Can anyone point out my mistake here? javascript $(document).ready(fu ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

Uploading custom images with a WordPress widget

I have been occupied with developing my own WordPress Widget, and almost everything is functioning smoothly except for the WordPress media uploader. I have incorporated eight buttons and input text fields to store the URL of the uploaded image. The click ...

Issue with `npm run watch` failing to compile when the data source is turned

Currently, I am faced with a challenge while working on Laravel and utilizing various node packages for development. The issue at hand is my limited internet connectivity. Every time I attempt to execute npm run watch, it refuses to initiate unless I am c ...

Error Encountered When Running JavaScript Code

Running the code on my Localhost:3000 is resulting in an error message: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'id') The specific section of the code causing this error is highlighted in the Source part: ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

Run a Python script to capture mouse coordinates using Selenium

Greetings, I am currently utilizing selenium webdriver to retrieve the X,Y coordinates of the cursor at a specific moment on the webdriver screen. However, I am facing challenges with the implementation of a method that involves using driver.execute_script ...

Stop processing the current websocket connection once a new websocket request is received

Currently, I am utilizing the npm ws module (or its wrapper named isomorphic-ws) for establishing a websocket connection. NPM Module: isomorphic-ws This setup allows me to retrieve an array of data from a websocket++ server situated on the same local mac ...

Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some t ...

The sticky element should only be active when the visible section is overflowing vertically. There should be no scrollbar if the height is minimal

I'm currently working on a Whatsapp-style navigation bar and facing an issue with the sticky navbar functionality. https://i.stack.imgur.com/Cy3lA.gif Please refer to the details below for more information. To resolve this issue, I have included ...