Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this?

BaSiderbarService:

    (function() {
  'use strict';

  angular.module('BlurAdmin.theme.components')
      .provider('baSidebarService', baSidebarServiceProvider);

  /** @ngInject */
  function baSidebarServiceProvider() {




    var staticMenuItems = [];

    this.addStaticItem = function() {
      staticMenuItems.push.apply(staticMenuItems, arguments);
    };

    /** @ngInject */
    this.$get = function($state, layoutSizes) {
      return new _factory();

      function _factory() {
        var isMenuCollapsed = shouldMenuBeCollapsed();

        this.getMenuItems = function() {
          var states = defineMenuItemStates();
          var menuItems = states.filter(function(item) {
            return item.level == 0;
          });

          menuItems.forEach(function(item) {
            var children = states.filter(function(child) {
              return child.level == 1 && child.name.indexOf(item.name) === 0;
            });
            item.subMenu = children.length ? children : null;
          });

          return menuItems.concat(staticMenuItems);
        };

        this.shouldMenuBeCollapsed = shouldMenuBeCollapsed;
        this.canSidebarBeHidden = canSidebarBeHidden;

        this.setMenuCollapsed = function(isCollapsed) {
          isMenuCollapsed = isCollapsed;
        };

        // The method I need to call in another controller    
        this.getStorage = function(){
            console.log(localStorage.user);
        }

        this.isMenuCollapsed = function() {
          return isMenuCollapsed;
        };

        this.toggleMenuCollapsed = function() {
          isMenuCollapsed = !isMenuCollapsed;
        };

        this.getAllStateRefsRecursive = function(item) {
          var result = [];
          _iterateSubItems(item);
          return result;

          function _iterateSubItems(currentItem) {
            currentItem.subMenu && currentItem.subMenu.forEach(function(subItem) {
              subItem.stateRef && result.push(subItem.stateRef);
              _iterateSubItems(subItem);
            });
          }
        };

        function defineMenuItemStates() {
          return $state.get()
              .filter(function(s) {
                return s.sidebarMeta;
              })
              .map(function(s) {
                var meta = s.sidebarMeta;
                return {
                  name: s.name,
                  title: s.title,
                  level: (s.name.match(/\./g) || []).length,
                  order: meta.order,
                  icon: meta.icon,
                  stateRef: s.name,
                };
              })
              .sort(function(a, b) {
                return (a.level - b.level) * 100 + a.order - b.order;
              });
        }

        function shouldMenuBeCollapsed() {
          return window.innerWidth <= layoutSizes.resWidthCollapseSidebar;
        }

        function canSidebarBeHidden() {
          return window.innerWidth <= layoutSizes.resWidthHideSidebar;
        }
      }

    };

  }
})();

This is the module where I want to inject the service and use the method, DashboardModule:

    /**
 * @author v.lugovsky
 * created on 16.12.2015
 */


(function() {
    'use strict';

    angular.module('BlurAdmin.pages.dashboard', [])
        .config(routeConfig);

    /** @ngInject */
    function routeConfig($stateProvider) {

        // Calling the service here
        baSidebarService.getStorage()

        $stateProvider
            .state('dashboard', {
                url: '/dashboard',
                templateUrl: 'app/pages/dashboard/dashboard.html',
                title: 'Dashboard',
                resolve: {
                   user: function(baSidebarService){ 

                console.log('DASHBOARD',baSidebarService.getStorage())
                }
            },
                sidebarMeta: {
                    icon: 'ion-android-home',
                    order: 0,
                },
            });
    }

})(); 

Is there a way to accomplish this? I need to retrieve this method to apply logic based on its value.

Answer №1

Utilize the service:

    /** @ngInject */
    function configureRoutes($stateProvider, sidebarService) {

        // Use the service in this section
        sidebarService.fetchData()

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

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

Unable to set custom claims using Firebase Auth's setCustomClaims() method

I am encountering an issue with setting custom claims for Firebase Authentication service's token. I am using a Cloud function to establish the custom claims for Hasura. The cloud function is triggered upon the creation of a new user to set the custom ...

Encountering issues with running the 'npm run serve' command locally in a Vue project

Trying to develop an app with Vue, I used the npm command. However, when I executed "npm run serve," the messages showed me that I should be running the app at "http://localhost:8080/" and not on "x86_64-apple-darwin13.4.0:". Is there a way to fix this by ...

jQuery Files in Conflict

The issue I am facing involves the code below. The first function requires linked js and css, while the second one needs a jQuery and javascript file inherited from base.html. However, there seems to be a conflict in loading these files (possibly because o ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

The AngularJS ui-bootstrap modal challenge with instances

Encountering an issue with my AngularJS app (version 1.4.7) and the latest version of ui.bootstrap. The problem arises when attempting to inject $uibModalInstance, resulting in the error message Unknown provider: $uibModalInstanceProvider Below is the con ...

Selecting keys of an object in Angular 2

Attempting to fetch data from an API using key selection but encountering retrieval issues. File: app/app.component.ts import {Component, OnInit} from 'angular2/core'; import {Http} from 'angular2/http'; import {httpServiceClass} fro ...

What is the behavior of the JavaScript event loop when a Promise's resolution is tied to setTimeout?

console.log('1') setTimeout(() => { console.log('2') }, 0) function three() { return new Promise(resolve => { setTimeout(() => { return new Promise(resolve => resolve('3')) },0) ...

Using Express in Node.js to send a GET request to a different server from a Node route

When a client triggers a GET request by clicking a button on the index page, it sends data to a route that is configured like this: app.js var route = require('./routes/index'); var button = require('./routes/button'); app.use('/ ...

Utilizing AngularJS for manipulating a multidimensional array with interdependent select boxes

I have a unique collection of product names along with their respective versions stored in a multidimensional array. My goal is to design an interactive interface that allows users to first select a product from a drop-down menu and then choose the version ...

How can I animate scrolling up or down using jQuery and CSS?

I have a a element that triggers an action when clicked: <a href="#" class="hel" onclick="YPCP1_();">Scroll down</a> Also, function YPCP_(){ var scroll = $(window).scrollTop(); window.scrollTo(0, 600); } The function successfully sc ...

Node.js can be utilized to make multiple API requests simultaneously

I am facing an issue while trying to make multiple external API calls within a for loop. Only one iteration from the for loop is sending back a response. It seems that handling multi-API requests this way is not ideal. Can you suggest a better approach fo ...

The value could not be retrieved because the input name depends on the array index

To determine the name of the input based on the array index, use the following method: <div id="editAboutSantences<%=i%>" class="edit-container"> <div class="input-container"> <label> content: </label> ...

Saving base64 encoded pdf on Safari

I am facing an issue with a POST call that returns a base64 PDF. The problem arises when trying to convert it to a Blob and download it using Safari browser. This method works perfectly in all other browsers. openPdf = () => { const sendObj = { ...

Is it possible to declare a variable as both $rootScope and $scope within the same controller?

Is it possible to declare a variable as both $rootScope and $scope in the same controller? $scope.Account=[{'sdfdsf','sdfds'}]; $scope.refreshAccountSummary = function () { Report.account(function (res) { $rootScope.Account ...

Is there a way to horizontally center Material UI Switch and its icon props?

I'm using Material-UI to implement a Switch component on my project. This particular component allows for the addition of icons, however, I've encountered an issue with alignment when including them. Is there a way to horizontally center align b ...

Unable to loop through using ngFor

I have a component that retrieves data from the back-end and groups it accordingly. Below is the code snippet: getRecruitmentAgencyClientPositions(): void { this._recruitmentAgencyClientsService.getRecruitmentAgencyClientPositions(this.recruitmentAge ...

Instructions for executing the ng command in Ubuntu

Recently, I installed nodejs on my Ubuntu 16.04 using the commands: sudo apt-get update sudo apt-get install nodejs sudo apt-get install npm To verify the installation, I ran the command which nodejs and it returned /usr/bin/nodejs My goal is to run ...

Building routes for nested relationships in the MEAN stack: A comprehensive guide

Within my Mongoose Schema, I am dealing with two models - User and Plans. Each user can have multiple plans, so in the Plans Schema, I am embedding a userID like this: var PlanSchema = new mongoose.Schema({ title: {type: String}, userId: {type: Stri ...

tutorial on updating database status with ajax in Laravel

Currently, I am using Laravel in my project and I need to modify the patient's status when they schedule an appointment with a doctor. The patient can have one of three statuses: Accept, Waiting (automatically assigned when the patient selects a date ...