AngularJS: Controller isn't being triggered

I'm encountering a peculiar issue with AngularJS where MainCtrl is not functioning at all. When I visit localhost/, it automatically redirects to localhost/#/ but the page remains blank. There are no error messages in the console, and I can confirm that /views/main.html is accessible to the public. I'm unsure why this is not working. Is there something crucial that I'm overlooking?

angular.module('TurkApp', ['ngCookies']).config([
  '$routeProvider',
  function ($routeProvider) {
    $routeProvider.when('/', {
      templateUrl: '/views/main.html',
      controller: 'MainCtrl'
    }).otherwise({ redirectTo: '/' });
  }
]);
  angular.module('TurkApp', []).controller('MainCtrl', [
    '$scope',
    '$http',
    '$location',
    '$cookies',
    function ($scope, $http, $location, $cookies) {
      $scope.questionIsLoading = true;
      $scope.answerButtonsDisabled = true;
      $scope.showHelp = false;
      $scope.currentRetries = 0;
      $scope.acceptedHit;
      $scope.currentQuestionText = null;
      $scope.currentQuestionID = null;
      var AssignmentID, Interest;
      var getInterest = function () {
        return $cookies.interest;
      };
      var getAssignmentID = function () {
        var qsRegex = new RegExp('(?:\\?|&)AssignmentID=(.*?)(?=&|$)', 'gi'), m, assignmentID = false;
        while ((match = qsRegex.exec(document.location.search)) != null) {
          assignmentID = match[1];
        }
        if (!assignmentID) {
          assignmentID = $location.search()['AssignmentID'];
        }
        $scope.acceptedHit = assignmentID == 'ASSIGNMENT_ID_NOT_AVAILABLE' || !assignmentID ? false : true;
        return assignmentID;
      };
      $scope.loadNextQuestion = function () {
        $scope.questionIsLoading = $scope.answerButtonsDisabled = true;
        $http.get('/workers/' + Interest + '/next-question').success(function (data, status) {
          $scope.currentQuestionText = data.text;
          $scope.currentQuestionID = data.id;
          $scope.questionIsLoading = $scope.answerButtonsDisabled = false;
        }).error(function () {
          console.log('Answer send failed');
        });
      };
      $scope.sendAnswer = function (answer) {
        if (!$scope.questionIsLoading && !$scope.answerButtonsDisabled) {
          $scope.questionIsLoading = $scope.answerButtonsDisabled = true;
          $http.post('/workers/' + Interest + '/answer-question', {
            question_id: $scope.currentQuestionID,
            question_text: $scope.currentQuestionText,
            answer: answer
          }).success(function (data, status) {
            $scope.loadNextQuestion();
          }).error(function () {
            console.log('Answer send failed');
          });
        }
      };
      $scope.toggleHelp = function () {
        $scope.showHelp = $scope.showHelp ? false : true;
      };
      var init = function () {
        AssignmentID = getAssignmentID();
        Interest = getInterest();
        $scope.loadNextQuestion();
      };
      init();
    }
  ]);

Answer №1

It appears that you are initializing the 'TurkApp' module twice, causing the loss of configuration from the first module:

angular.module('TurkApp', ['ngCookies'])

By providing the second parameter to the angular.module function, a new module is created. If the second parameter is omitted, it assumes the module already exists and extends it.

Instead of:

angular.module('TurkApp', [])

Try using:

angular.module('TurkApp')

For more information, refer to the usage section on this page - http://docs.angularjs.org/api/angular.module

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

The JavaScript program for the shopping list is experiencing issues with the formatting of list items

I have been working on developing a shopping list program using JavaScript. The program includes an input box and an "add item" button, which adds the text entered in the input field to an unordered list as a list item. Each list item also contains an imag ...

Discover the best way to sort products by category

I'm in the process of developing an online store where customers can choose from three options: "body lotion," "body wash," and "body scrub." Once a selection is made, the corresponding product will be displayed. The products are stored in an array n ...

Extracting the month and year from a datetime string: A simple guide

I am working with a JSON object that includes a field called Month with a string datetime value- { Month : "31-Jan-2022 12:00 AM (EST)" .... .... } Is there a way to extract the Month Name and Year from this string using JavaScript's dat ...

Retrieving information from Flask server using an Ajax request

Exploring Flask and Ajax, my server-side web application is meant to double and return a passed number. I adapted the code from the example on Flask's site, resulting in this Python snippet: from flask import Flask, request, jsonify # Initialize the ...

ReferenceError: _jquery2.default.ajax is not a function" encountered in a React Native application

I have been attempting to use jQuery to retrieve xml data from an internal website. My expo project setup is quite basic and resembles the following: import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; imp ...

Enhancing user interfaces with jQuery by updating DOM elements

Can anyone help me figure out how to update a webpage so it functions as a report that multiple people can contribute to? I'm using forms to collect data and want it to instantly display under the correct category headings. Currently, I'm using j ...

How can I attach events to newly generated elements without using jQuery?

If I want to dynamically add a form to my webpage (through AJAX or other JavaScript methods), how can I attach event listeners to these elements before they actually exist on the page? When using jQuery, it's simple to bind the events to a parent ele ...

Having trouble with json_decode in PHP? Learn how to effectively retrieve JSON data in PHP

My attempt to update content using Angular on the front-end and PHP on the server side is encountering some issues. Below is the code snippet being used: In the main js file, a call for update: updateinscription: function($params) { var urlphp = "ht ...

Locate each document in MongoDB that pertains to a time period of

I have been trying to fetch data for the past n days. For instance, I am interested in retrieving data from the last 3 days. However, after following a solution I found on StackOverflow, I am only able to retrieve one document instead of all the documents. ...

Toggle the checkbox to either select or deselect the value

I am attempting to toggle the value of a checkbox. When checked, the value should be set to active, and when unchecked, it should be set to disabled. The current code successfully changes text based on the checkbox status, but the issue is that the value ...

What is the best way to create a Promise that is fulfilled when an event is emitted by an event emitter in JavaScript or Node.js?

Is there a way to create a Promise in Node JS that will only resolve when a specific event is emitted by an event emitter? I am trying out the following code snippet, but I am unsure how to make the promise wait until the event occurs. function bar(resol ...

Ajax script causes error 403 when loading content while scrolling

Currently in the process of creating a blog using the HubSpot platform. The primary goal is to have blog posts load dynamically as users scroll down the page. I came across a script that claims to achieve this functionality and is designed specifically for ...

Click on a button to send the React Router path as a parameter in

I've got a React form with a submission button like this: <Link className="btn btn-secondary btn-width-200 search-submit" to={{pathname: '/booking/search', query: this.state.filters}}> Search </Link> Within the ...

Choosing the right framework for a web application

Currently, I am at a crossroads when it comes to deciding on the architecture of the web application I will be developing. As part of a small team, I am tasked with working on this project solo while my colleagues focus on other tasks. The front-end of th ...

I am in the process of transforming my basic JS Array into one that contains key/value

Currently, I am utilizing jQuery to create an Array in the following manner: var arr = new Array(); $('#some-form .some-input').each(function() { arr.push($(this).val()); ...

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

Tips on finding the key associated with a specific value

When a form is submitted, one of the fields being sent is an ID number instead of the name for easier processing by the server. For example: HTML dropdown select <select ng-model="myColor" class="form-control" ng-options = "color.ID as color.color ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

KineticJs: Enhancing Rotation with Multitouch Capability

Currently, I have a click event implemented in my code that rotates my puzzle piece by 90 degrees when clicked. However, I would like to change it from a mouse click to a touch event. How can I achieve this? Thank you. piecesArray[i][j].shape.on("mous ...

Link clicking does not trigger URL routing properly

I've been tasked with updating our web application, and I'm facing a challenge that I need help with. My boss wants users to be able to click on a link in an email and have the internal company web app directly navigate to a specific page indicat ...