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

I'm having trouble with my AJAX Update Panel. Can someone please help me figure out what I'm doing wrong?

--------------Handling Gridviews DataBound Event ----------------- protected void grdShowCallingList_DataBound(object sender, EventArgs e) { if (grdShowCallingList.Rows.Count > 0) { foreach (GridViewRow row in grdShowCallingList.Rows) ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

What could be causing the JSON.stringify() replacer function to fail?

Here is the code snippet I'm working with: http://jsfiddle.net/8tAyu/7/ var data = { "foundation": "Mozilla", "model": "box", "week": 45, "transport": { "week": 3 }, "month": 7 }; console.log(JSON.stringify(data, ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

I'm curious about the correct method for updating a parent component using a shared service within the ngOnInit function in Angular version 13

There have been instances where I encountered a scenario multiple times, where I utilize a shared service within the ngOnInit of a component to update a value in another component, specifically its parent. This often leads to the well-known Error: NG0100: ...

javascript functionality may be affected in Internet Explorer and Firefox following the upgrade to jquery version 1.8.3

After upgrading to jquery 1.8.3 from jquery 1.7 (where everything was functioning properly in all browsers), I added a javascript plugin that specifically requires jquery 1.8.2 or 1.8.3 Unfortunately, the image resizing functionality of this javascript is ...

What causes the picturesArray to remain consistently void?

const fetch = require("node-fetch"); let images = []; fetch('http://www.vorohome.com//images/assets/159314_887955.png') .then(response => response.buffer()) .then(buffer => { const data = "data:" + response.headers.get ...

Angular: Intercept Drag and Drop Actions

I am utilizing angular-ui to create a sortable list using "drag and drop" functionality, and it is functioning perfectly. Here is an example of how it works: index.html <ul ui-sortable ng-model="list"> <li ng-repeat="item in list" class="it ...

Attempting to send arguments to a jQuery ajax request

After successfully implementing my original ajax call, I decided to create a reusable function for it. This way, I can easily modify the data and URL fields of the ajax call without having to retype everything each time. However, I encountered an issue whe ...

Clicking the button will trigger the onclick event

I'm working on a button component in TypeScript and I have encountered an issue with passing the event to the submitButton function. import * as React from 'react'; interface Props { className?: string; text: string; onClick?(event: Reac ...

A step-by-step guide to adding a checkbox column dynamically within handsontable

I am currently utilizing handsontable within a jsfiddle at http://jsfiddle.net/kc11/cb920ear/1/. My task involves dynamically inserting a checkbox column before the existing data. The structure I am working with appears to be a multidimensional array, as s ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

Steps to retrieve values from a grid and execute a sum operation using PROTRACTOR

Embarking on my Protractor and Javascript journey, I am faced with the challenge of writing a test script to retrieve values of various accounts under the header "Revenue" (as shown in the image below). My task involves extracting all number values listed ...

Attempting to remove an attribute or property in JavaScript will not yield the desired result

When I try to close the menu after opening it, the inline style won't get removed despite trying different methods. The CSS only has text properties for alignment and the class can-transform contains a media query. That's all the information I h ...

What is the best way to transfer a JSON response from one HTML page to another using AngularJS?

Currently, I have an API with search functionality written in Laravel PHP. When a user types a string into the input field and clicks on the search button, a JSON response is generated. My goal now is to open a new HTML page named "search.html" upon click ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Issue: Retrieve comments via AJAX (from database) in Laravel 5.2

Currently, I am developing a comments section for posts where users can leave comments without the need to refresh the page. However, I am facing an issue in displaying these comments instantly on the post without any page refresh. This is how I have stru ...

I am utilizing Vuex to store all of the product details and handle API request queries efficiently

Question regarding Vue/Vuex efficiency and best practices. I am working with an API that returns a paginated data-set of 50 products, which I am storing in a Vuex store. When displaying all products, I iterate over the Vuex store. Now, for individual pr ...

Learn how to utilize ng-class to assign an ID selector to HTML elements

In my code, I have an icon that is displayed conditionally using ng-class. I am looking to include ID's for both the HTML elements. <i ng-show="ctrl.data.length > 1" ng-class="{'glyphicon glyphicon-chevron-down': !ctrl.isOpen, ...