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

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...

Is it possible to alter the video dynamically according to the state in Vuex?

I am working on a small web application that mimics the appearance of FaceTime. My goal is to switch between video elements by clicking a "Next" button, which will update a value in Vuex and swap out the video accordingly. I initially attempted this appr ...

What steps do I need to take to translate jQuery code into standard JavaScript code?

Can someone please help me convert this jQuery code to plain JavaScript? window.addEventListener('scroll', function() { document.querySelectorAll('.container p').forEach(function(el) { var scrollTop = window.scrollY, ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Attempting to create a Next.js 13 application, but struggling with using the client-side functionality

Exploring Next.js for the first time, I embarked on creating a simple application. Everything was going smoothly until I attempted to include a "use client" tag at the beginning of a component to utilize certain hooks. This resulted in the app breaking and ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

Incorporate pug and sass into your React project for a more

Are pug/jade and sass compatible with react? I enjoy organizing my code by separating files, and the functionality that sass and pug provide is great for this purpose. Is there a way to integrate pug and sass into a react project? Pug example: doctype ...

Is it possible to achieve a smooth transition to the right using CSS

I'm attempting to create a sliding box effect from left to right using only transitions, similar to this: #box { width: 150px; height: 150px; background: red; position:absolute; transition: all 2s ease-out; right:auto; } .active{ bac ...

Is there a way to access an Excel file with JavaScript without relying on the ActiveX control?

Is there a way to access an Excel document using JavaScript code without relying on an ActiveX control object such as shown below: var myApp = new ActiveXObject("Excel.Application"); myApp.workbooks.open("test.xls"); ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

Certain individuals are experiencing difficulties accessing my Google application

I have created a node.js application with a Google login feature using the following packages: "passport": "^0.3.2" "passport-google-oauth": "^1.0.0" However, I am facing an issue where only a few users are able to access this feature. Below is the code ...

Error discovered in Webpack syntax

I'm a newcomer to webpack and feeling lost on how to properly configure the settings. Here is my project structure: / -- /public -- /js -- app.js -- /css -- app.scss -- /node_modules -- /autoprefixer -- /babel-loader ...

Difficulty encountered when trying to template routes with more than one slash in Angular-route

I'm encountering difficulties with my Express+Jade+AngularJS[v1.2.22] application when attempting to access routes such as "mydomain.com/something/somethingelse" or "mydomain.com/something/another/last", which include one or more path subdivisions. T ...

Learning how to integrate Next.js, React.js, and Redux into an HTML page for an enhanced user

My current project is built on Asp.Net MVC, but the technology used is not crucial. I integrated react.js and redux for searching a section of my html page using a cdn link. Now, I am considering deploying the server side of the application with next.js. ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

Error in AngularJS: Loading null value for an option tag

I have successfully bound all the values to the option tags using Angular JS. However, I am facing an issue where a null value is getting appended on load. Additionally, when I set a value in my JavaScript code, it only sets the first value and does not ch ...

How can I show the total sum of input values in a React.js input box?

Is there a way to dynamically display the sum of values entered in front of my label that updates automatically? For example, you can refer to the image linked below for the desired output Output Image I have initialized the state but I'm struggling ...

Elevate javascript

How can I create a new constructor that will alert the increment value? Any suggestions on how to achieve this? This is the current code snippet: var increment = new Increment(); alert(increment); /* 1 */ alert(increment); /* 2 */ alert(increment + incr ...

Utilizing Async / Await in the created lifecycle hook - Vue2

I recently installed the vue-element-loading package and added its component to my page.vue: <vue-element-loading :active="isActive" :is-full-screen="true"/> After adding a variable to my data: data () { return { isActive: false, } } I th ...