Am I on the right track with my service definition in Angular?

(function(){
    angular.module('myApp',[])
})();

(function(){
    angular.module('myApp.dashboard',[])
})();

(function(){
    angular.module('myApp.value',[])
})();

(function(){
    'use strict';
    angular.module('myApp.value').service('whichToShow',function(){
        alert("running2");
        var logged=true;
        return {
            getVar: function(){
                return logged;
            },
            setVar: function(value){
                logged=value;
            }

        };
    });
})();

(function(){
    'use strict';
    angular.module('myApp.dashboard').controller('mainControl',mainControl);

    mainControl.$inject = ['whichToShow'];
    alert("running1");
    function mainControl(whichToShow){
        this.logged=whichToShow.getVar();
        alert(this.logged);

    };
})();

I am currently developing an app inspired by another existing app, but I am having trouble using a newly defined service. I have been following the code structure of the original app found here. Can you guide me on which part of my code needs modification? It would be helpful if you could make adjustments directly to my code so that I can understand where I went wrong. Thank you!

You can access all of my code in the following link: https://plnkr.co/edit/YeahrG28bT2izX8gMKor?p=preview I have made limited progress so far and my current goal is to hide certain buttons on the interface.

Answer №1

The whichToShow variable is specified in the myApp.value module, but it is being used in the myApp.dashboard module. To resolve this, simply include a reference to the myApp.value module when declaring the myApp.dashboard module.

angular.module('myApp.dashboard',['myApp.value'])

Answer №2

Your content is presenting a concept of a factory, which involves obtaining an instance and enhancing it with methods.

If you want to transform your existing service into a factory, you can do so by following this example:

(function(){
    'use strict';
    angular.module('myApp.value').factory('whichToShow',function(){
        alert("running2");
        var logged=true;
        return {
            getVar: function(){
                return logged;
            },
            setVar: function(value){
                logged=value;
            }
        };
    });
})();

Alternatively, if you prefer to define your service differently, you may consider the following approach:

(function(){
    'use strict';
    angular.module('myApp.value').service('whichToShow',function(){

        var logged=true;
        this.getVar = function(){
                return logged;
            };
        this.setVar =function(value){
                logged=value;
            };
    });
})();

Note:

The code in your Plunker example contains errors that need to be rectified. Please refer to this corrected version: https://plnkr.co/edit/2HAwy7MV4dK0yUuBcCfG?p=preview

  • Ensure that your inclusion of all.js points to the correct location, without specifying the directory path.

  • In your mainControl, verify the correctness of your dependency injection.

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

TaffyDB is throwing an error message indicating that TAFFY is not recognized as a function

I am currently developing a web-based game using HTML, CSS & JavaScript within Visual Studio and utilizing TaffyDB as my database. However, I have encountered an error when trying to create a database using the TAFFY function, as it keeps showing up in the ...

You can use AJAX, JQuery, or JavaScript in PHP to upload a total of 7 files by utilizing 7 individual file input

My client has a unique request - they want to be able to upload a file in PHP without using the traditional <form> tag or a submit button. While I am familiar with file uploads in PHP, I am unsure of how to achieve this without utilizing the <for ...

Images are not loading when linking Angular $compile to a controller

Would love some assistance with rendering a gallery in a bootstrap modal-box. I have put together a template using ng-init to load the images. It works perfectly for the first page, displaying all images and captions. However, on the second page (click to ...

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this: app.component.ts: import { Component, OnInit } from "@angular/core"; import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from ...

Switching between light and dark themes in a Next.js application with Ant Design v5 theme toggle

In my Next.js application using Ant Design v5, I am working on implementing a dynamic theme toggle to switch between light and dark modes. The issue I'm facing is that the initial theme settings work correctly, but subsequent changes to the isDarkMode ...

Spring Security does not support PUT requests with AngularJS and Spring Boot

Creating an Angular controller function $scope.updatePatient = function() { var patient = new patientUpdateService({id:"15", name:"m",lastname:"s"}); patient.$update(); } Defining an Angular service .factory("patientUpdateServic ...

Creating a Cubic Bezier Curve connecting two points within a 3D sphere using three.js

I'm currently working on a project where the user can click on two points on a sphere and I want to connect these points with a line along the surface of the sphere, following the great circle path. I have managed to obtain the coordinates of the sele ...

Troubleshooting problem with Ajax responseText

Can an ajax responseText be received without replacing the existing content? For instance: <div id="content"> <p>Original content</p> </div> Typically, after running an ajax request with a responseText that targets id="conten ...

Passing Data from $http.get to Angular Controller Using a Shared Variable

One issue I'm facing is the inability to pass the content of a variable inside $http.get() to the outside scope, as it always returns undefined. I attempted using $rootScope, but that approach was not successful. controller('myControl', fu ...

How to use jQuery to delete the final table in an entire HTML document

This situation is really frustrating: When I make a jQuery Ajax call, the success callback returns an entire HTML page. The returned page looks like this: <html> <head> <title>Title</title> <body> <table></table> ...

Displaying a portion of a React functional component once an asynchronous function call has been successfully executed

I am currently using material-ui within a React function component and have implemented its Autocomplete feature. I have customized it so that when the text in the input field changes, I expect the component to display new search results. callAPI("xyz") I ...

Creating dependent dropdowns using Laravel Inertia Vue: A step-by-step guide

In my AddressController, I have a function called loadCity along with other CRUD functions: public function loadCities(Request $request) { $provinceId = $request->province_id; $cities = Province::where('province_id' ...

Leaving the pipeline of route-specific middleware in Express/Node.js

My implementation involves a sequence of "route specific middleware" for this particular route: var express = require('express'); var server = express(); var mw1 = function(req, resp, next) { //perform actions if (suc ...

Issues with implementing KoGrid within the Durandal JS framework

How do I properly bind a koGrid in my Durandal JS view page? The code provided below is not functioning as expected. View (HTML) <div id="functiontable" class="form-actions"> <div style="height: 200px" data-bind="koGrid: ...

Angular/Karma Unit Test for HttpClient

During my research on unit testing, I came across some very useful examples. Most of the examples focus on unit testing functions that interact with Angular's HttpClient, and they usually look like this: it('should return an Observable<User[] ...

Ways to update list item text with jQuery

I am attempting to create a button that can replace the content of a list item. Although I have looked at other solutions, I keep encountering this error message: Uncaught TypeError: Object li#element2 has no method 'replaceWith' I have experime ...

Unable to transfer all the formatting from the original file for the window.print() function. Localhost is functioning properly, but encountering issues with production

I'm encountering an issue with getting all styles from my Vue app. I have tried the code provided in this answer: https://stackoverflow.com/questions/52343006/how-to-print-a-part-of-a-vue-component-without-losing-the-style While it works fine on loc ...

Issue: Attempting to write data after reaching the end in Node.js while using

I have encountered the following error: Heading Caught exception: Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (/home/projectfolder/node_modules/express/node_modules/connect/lib/mid ...

Steps for creating a function to validate if two classes are identical

Currently, I am developing a memory game using JavaScript. One of the features I have implemented is toggling between two card faces by changing the class back and forth. Now, I am in the process of creating a function that will check if two game cards are ...