Having trouble loading services within my Angular controller

After developing my Angular application, I added some basic code to my controller which is displayed below. Now, I am attempting to include two services that I created in my services.js file. This file is being loaded in my index.html and required within my controllers.js file. Strangely, I am unable to access the namespaces passed in, and I cannot seem to identify the reason behind this issue. Despite not encountering any errors and following tutorials with similar setups, I am puzzled by this situation. Any suggestions or solutions would be greatly appreciated. Thank you :)

Controllers.js

angular.module('starter.controllers', ['services'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout, Auth, socket) {
  // Form data for the login modal
  $scope.loginData = {};
  debugger // i dont have access to Auth or socket
  // Create the login modal that we will use later
  $ionicModal.fromTemplateUrl('templates/login.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.modal = modal;
  });

  // Triggered in the login modal to close it
  $scope.closeLogin = function() {
    $scope.modal.hide();
  };

  // Open the login modal
  $scope.login = function() {
    $scope.modal.show();
  };

  // Perform the login action when the user submits the login form
  $scope.doLogin = function(user) {
    console.log('Doing login', $scope.loginData);
    debugger // I dont have access to Auth or socket
    // Simulate a login delay. Remove this and replace with your login
    // code if using a login system
    $timeout(function() {
      $scope.closeLogin();
    }, 1000);
  };
})

Services.js

var baseUrl = 'http://localhost:3000';

angular.module('services', [])

.factory('socket', function socket($rootScope) {
  var socket = io(baseUrl);

  return {
    on: function(eventName, cb) {
      socket.on(eventName, function() {
        var args = arguments;
        $rootScope.$apply(function () {
          cb.apply(socket, args);
        });
      });
    },
    emit: function(eventName, data, cb) {
      socket.emit(eventName, data, function() {
        var args = arguments;
        $rootScope.$apply(function () {
          if (cb) cb.apply(socket, args);
        });
      });
    }
  };
})


.factory('Auth', function Auth($q, $http) {
  var user = null;

  var login = function login (name, password) {
    var defer = $q.defer();

    var url = baseUrl + '/login';
    var postData = { name: name, password: password };

    $http.post(url, postData).success(function(response) {
      if (response.success && response.success === true) {
        user = { name: response.name, id: response.id };
        window.localStorage.setItem('user', JSON.stringify(user));
        return defer.resolve(response);
      } else {
        return defer.resolve('No user found');
      }
    }).error(function(err) {
      defer.reject(err);
    });

    return defer.promise;
  }

  var currentUser = function currentUser (user) {
    return user;
  }

  var logout = function logout () {
    user = null;
    window.localStorage.removeItem('user');
  }

  return {
    login: login,
    logout: logout,
    currentUser: currentUser
  };
});

Answer №1

Have you verified that you have included both ng-app and ng-controller in your HTML code? Here is an example:

<!DOCTYPE html>
<html lang="en" ng-app="starter">
<head>
  <meta charset="UTF-8">
  <title>Sample App</title>
</head>
<body ng-controller="starter.controllers">
  <!-- Your code here -->
  <script type="text/javascript" src="app.js"></script>
  <script type="text/javascript" src="controller.js"></script>
  <script type="text/javascript" src="service.js"></script>
</body>
</html>

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

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Unable to modify the value of an HTML dropdown list

My latest project is a website located at pg.wcyat.me (Source code), where I utilized github.com/thdoan/pretty-dropdowns for dropdown menus. Using JavaScript, I am able to dynamically change the values of select lists. For example: document.getElementById( ...

Determine the frequency of a specific letter in JavaScript by utilizing the indexOf method

Hey there! I'm currently working on a code to count the occurrences of a specific letter in a string using indexOf(). However, it seems like something may be off with my implementation. Can anyone point me in the right direction? Thanks! var string = ...

Angular JS can customize the default HTML page on a select tag, offering users a

When the web page is loaded, I want to display the default tableView.html from the views folder. However, it is not working as expected. Interestingly, when I switch between "Table View" and "List View" in the dropdown menu, it works fine. I believe the ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Turning text into clickable links using JavaScript

I am faced with a scenario where I need to detect phone numbers within a string and convert them into clickable links. At the moment, using an external library is not an option. Here's the progress I've made so far: String: "This is my phone nu ...

Tips for implementing an HTML modal with AngularJS binding for a pop up effect

As a beginner in AngularJS, I am facing a challenge. I have an HTML page that I want to display as a pop-up in another HTML page (both pages have content loaded from controllers). Using the router works fine for moving between pages, but now I want the s ...

Using Angular's ui-router to achieve a dynamic view based on conditions

I have a question that is similar to the one asked here: UI Router conditional ui views?. However, my scenario is more intricate and I am struggling to make the suggested solution work for me. Essentially, I have a URL that can be displayed in two distinc ...

The disappearance of hashtag (#) when passed as req.query in the backend has been observed

I am facing an issue where a string with a hashtag in the req.query is not being parsed correctly as JSON. http://localhost:3000/link/?items=[{"quantity":1,"_id":"00001","box":"item01","desc":&quo ...

Using Javascript to trigger form submission using arrow keys

There are four forms displayed on a single page, and I want each form to be submitted based on the arrow key that is pressed. <form name='go_north' action='' method='post'> <input type='hidden' name=' ...

Troubleshooting: Missing Headers in AngularJS HTTP Requests

When I make a request using AngularJS like this: var config = { headers: { 'Authorization': 'somehash', 'Content-Type': 'application/json; charset=UTF-8' } }; $http.get('htt ...

Utilize Office Scripts to update values across numerous worksheets

Looking for ways to improve the performance of this script, as it currently takes 45 seconds to run. Any ideas? function main(workbook: ExcelScript.Workbook) { try { const sheets = workbook.getWorksheets(); for (let sheet of sheets) { const break ...

What is the best way to include a class in the <td> element of a dynamic table?

My goal is to sum up the values in a specific column of a dynamic table by attaching an id property to each row. I am specifically focused on assigning an id to each <td> in every row of the table. UPDATE: Although I have all 4 keys in the <td> ...

What is the best way to have react-bootstrap's Dropdown automatically open when hovering your mouse over it?

Looking for a simple solution. I want the dropdown to open when hovering over it, rather than clicking on it. Here is my current code: <Nav> <NavDropdown onMouseEnter = {()=> isOpen=true} open={isOpen} noCare ...

Extracting data from a webpage's dynamic table using Python with Selenium and

I am planning to extract the data from the JavaScript tables found in the following link: import codecs import lxml.html as lh from lxml import etree import requests from selenium import webdriver import urllib2 from bs4 import BeautifulSoup URL = &apo ...

Customize chrome's default shortcuts with JavaScript

I'm working on an application that requires me to override some shortcut keys in the Chrome browser. While I'm able to create custom shortcuts to trigger alerts like in this Stackblitz example, I'm having trouble overriding a few default sho ...

In React, what is the correct term for "selection boxes" when choosing multiple items in Finder?

I'm in search of a React component that allows me to select multiple elements on the screen by clicking, holding, and forming a square around them. I've tried searching for terms like 'selection box' and 'React select elements,&apo ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...