Working with AngularJS: Implementing a Service in a Controller

A service has been developed in AngularJS, but it is not being utilized in the controller.

Service.js

var appService = angular.module("appService", []);
appService.service("bddService", function() {

    var bdds = bdd;

    this.getBdds = function(){
        return bdds;
    };

    var bdd = [{
        id : 1,
        nom : "Activité commercial",
        desc : "Information de l'activité commercial de l'entreprise Bou."
    }];
});

Controller.js

(function(){
    var accueilCtrl = angular.module("accueilCtrl", ['appService']);

    accueilCtrl.controller('accueilCtrl', ['$scope', 'bddService', function($scope, bddService){

        $scope.bdds = bddService.getBdds(); // No error, but no data

    }]);
})();

The code exists in two separate files, and when combined into one file, it functions correctly (Service injection into controller with AngularJS). No errors are displayed in the console.

Answer №1

var bdds = bdd;

this.getBdds = function(){
    return bdds;
};

var bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];

By understanding the concept of variable hoisting in JavaScript, we can rearrange the code as shown below:

var bdd;
var bdds;
bdds = bdd;              // results in bdds being undefined

this.getBdds = function(){
    return bdds;
};

bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];

To avoid any issues with variable hoisting, it is recommended to structure the code like this:

var bdd = [{
    id : 1,
    nom : "Activité commercial",
    desc : "Information de l'activité commercial de l'entreprise Bou."
}];
var bdds = bdd;

this.getBdds = function(){
    return bdds;
};

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

Scroll automatically to the following div after a brief break

On my website, the title of each page fills the entire screen before the content appears when you scroll down. I am interested in adding a smooth automatic scroll feature that will transition to the next section after about half a second on the initial "ti ...

Filtering records in Sails.js through route parameters

As a newcomer to Sails.js, I'm delving into its capabilities and workings. My scenario involves three interconnected models through associations: Series.js -> Season.js -> and Episode.js. Series.js module.exports = { attributes: { /* ...

What could be causing the error 'i is not defined' in my Vue.js component script when using a basic for loop?

I have a task where I need to sort an array by version and then move all elements starting with 'ipad' to the end of the list. This code snippet is extracted from a single file Vue.js component: computed: { orderedUsers: function () { ...

Having issues transferring values from one page to another. Any suggestions to make it work correctly?

I currently have two pages within my website, one is called details.page and the other is maps.page. In the details page, I have set up a search input as shown below : <form method="get" id="form-search" data-ajax="true" action="maps.page"> ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Securing AJAX Requests: Encrypting GET and POST Requests in JavaScipt using Node.js

Looking for a way to secure ajax post and get requests using JavaScript. The process would involve: Server generates private and public key upon request Server sends the public key to client Client encrypts data with public key Server decrypts data wit ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

Stanza.io encountered difficulties in generating a WebRTC answer

I have successfully set up a realtime messaging website using ejabberd + stanza.io. Everything works perfectly, and now I want to integrate Webrtc audio/video using the jingle protocol. Below is the JS code I am using for connection: var client = XMPP.cre ...

Tips for excluding the HTTP OPTIONS request from being intercepted by the express.js authentication middleware

I have set up a backend API using express.js that interacts with an AngularJS single-page application. To secure access to specific resources, I am utilizing token authentication to verify clients. In order to validate whether the incoming request from th ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...

Tips for rearranging table columns using drag and drop in react js

I have been experimenting with various libraries to create a drag-and-drop feature for changing table columns order. Here is my current implementation: import React, { useState } from 'react'; import './list_de_tournees.css' const Table ...

I utilize ng-table for managing data in both admin and user interfaces, with distinct sources. The admin interface displays author data until refreshed

Using ng-table for both admin and user functionality within the same controller and view, each loading data from different URLs. However, there is an issue with data being reloaded from cache when accessing it, that I need to clear when a user logs out. C ...

Can hash routes be defined in next.js?

Previously, I created a modal component using <HashRouter> in react-router where the modal would become active or inactive based on the hash url. For example, the modal is inactive when the url is /route, but becomes active when the url is /route#m ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

There seems to be an issue with the integration of Bootstrap in my JavaScript file

Is there a way to ensure that each new data entry in the array appears next to each other rather than stacking beneath one another? This is a JavaScript file with HTML written in Bootstrap format. const collegeData = [{ name: "University of Penn ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

eliminate the common elements between two arrays in typescript/javascript

I have two lists of objects, each containing two fields: let users1 = [{ name: 'barney', uuid: 'uuid3'}, { name: 'barney', uuid: 'uuid1'}, { name: 'barney', uuid: 'uuid2 ...

Is there a way to simplify and optimize the code further?

Here is the code snippet from my index.blade.php: HTML @foreach($sesis as $sesi) <td>{{ $sesi->waktu }} <label class="switch switch-text switch-info switch-pill" id="label-switch{{ $sesi->id } ...

Simulating a service dependency in unit tests for AngularJS

I have a dependency on StorageFactory in my service CurrentUser. The constructor of this service sets the user to the value returned by StorageFactory.get, or to a default user value if nothing is returned. Now, I need to test this functionality. Although ...