AnguarJS is failing to execute the controller function

I am currently working on an AngularJS application and I am facing an issue with calling my controller in the app when a submit button is clicked. Below is a snippet of the code:

index.html

<!DOCTYPE html>
<html lang="en" ng-app="adminsuite">
<head>
    <meta charset ="utf-8">
    <title></title>
</head>
<body>
<script src="bundle.js" charset="utf-8"></script>
<div class="container">
    <div ui-view></div>
</div>


</body>
</html>

login.html

<div class="col-md-6 col-md-offset-3">
<h2>Login</h2>
<form name="form" ng-submit='login()' role="form">
    <div class="form-group" ng-class="{ 'has-error': form.username.$dirty && form.username.$error.required }">
        <label for="username">Username</label>
        <input type="text" name="username" id="username" class="form-control" ng-model="username" required />
        <span ng-show="form.username.$dirty && form.username.$error.required" class="help-block">Username is required</span>
    </div>
    <div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required }">
        <label for="password">Password</label>
        <input type="password" name="password" id="password" class="form-control" ng-model="password" required />
        <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
    </div>
    <div class="form-actions">
        <button type="button" ng-disabled="form.$invalid" class="btn btn-primary">Login</button>
    </div>
</form>

index.js

window.onpopstate = function (e) { window.history.forward(1); }
require('jquery/dist/jquery.js');
 require('bootstrap/dist/css/bootstrap.css');
 require('./content/common.css');
require('angular');
require('angular-ui-router/release/angular-ui-router.js');
 require('angular-route/angular-route.js');
require('angular-cookies/angular-cookies.js');
angular.module('adminsuite',  ['ui.router','ngCookies']).config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/');
$stateProvider
    .state('login', {
        url: '/',
        templateUrl: 'Login/login.html',
        controller: 'loginController'
    })
    // HOME STATES AND NESTED VIEWS ========================================
    .state('dashboard', {
        url: '/dashboard',
        templateUrl: 'views/dashboard.html',
    });

    // ABOUT PAGE AND MULTIPLE NAMED VIEWS =================================

});
require('./Login/loginController.js');

require('./services/loginAuthenticationService.js');
require('./services/UserServices.js');

loginController.js

angular
    .module('adminsuite')
    .controller('loginController', ['$location', '$rootScope', 'AuthenticationService', '$scope', '$state', function($location, AuthenticationService, $scope, $state) {
    $scope.login = function(){
        $scope.dataLoading = true;
        AuthenticationService.Login($scope.username, $scope.password, function (response) {
            if (response.success) {
                AuthenticationService.SetCredentials($scope.username, $scope.password);
                console.log('Login successful');
                //$rootScope.state = true;
                $state.go('dashboard');
            } else {
                console.log(response.message);
                $scope.dataLoading = false;
                //$rootScope.state = false;
            }
        });
    };
 }

]);

No errors are showing up in the browser console or command prompt.

Answer №1

Make a change to the login button found in login.html; adjust the attribute from type="button" to type="submit":

<button type="submit" ng-disabled="form.$invalid" class="btn btn-primary">Login</button>

Answer №2

After making the adjustment to exclude the $rootScope injector from the controller, the function started working properly without it being passed in as a parameter.

Answer №3

Make sure to assign your controller in the HTML part. Here is an example:

<!DOCTYPE html>
<html lang="en" ng-app="adminsuite">
<head>
    <meta charset ="utf-8">
    <title></title>
</head>
<body ng-controller="loginController">
<script src="bundle.js" charset="utf-8"></script>
<div class="container">
    <div ui-view></div>
</div>


</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

Tips for getting a jQuery script to activate after dynamically adding DOM elements with Ajax

I have some knowledge about the "on" method, but many of the answers I've seen are not very specific. Can someone assist me with this code? $(function(){ var pagePositon = 0, sectionsSeclector = 'article#sector', $scrollItems = $( ...

Tips for building a JavaScript promise chain using an array function

I encountered a strange problem while working on a JS promise chain. When using an arrow function with parentheses in the promise, I am not getting the expected value. Instead, it gives me an 'undefined' value in the second 'then'. Her ...

What's the importance of including (req, res, next) in the bodyParser function within Express?

My original use of bodyParser looked like this: app.use(bodyParser.json()); However, I now have a need to conditionally use bodyParser: app.use((req, res, next) => { if (req.originalUrl === '/hooks') { next(); } else { ...

When utilizing a clone in a Draggable and Droppable scenario, the data/attribute is obtained from the

Currently, I am struggling with retrieving data/attributes from the original item when using jQueryUI draggable/droppable to move rows between tables. I have set helper: 'clone' but am finding it difficult to access any data from the dragged item ...

Anyone have a sample showcasing the integration of VueJS with the latest webpack 4 configuration?

VueJs templates now come with numerous examples and starting project skeletons. However, most of them still utilize webpack v3. Has anyone experimented with webpack 4? I'd love to see how you integrate version 4 of webpack into a VueJs project. Thank ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

Having trouble with debugging Angular JavaScript code? The Model option in the Batarang debugger doesn't seem to be displaying the scope

I've been struggling to pinpoint the scope of AngularJS in Batarang. Despite spending a considerable amount of time debugging, I still can't seem to access the scope. Below is the HTML code snippet: <div data-ng-controller="RegisterCtrl" ...

Silence from PHP script after executing jQuery post() method

I've run into an issue while trying to retrieve data from a PHP file that reads a mySQL database. The data is delivered successfully when accessed through a browser: However, when attempting to access the data using jQuery's get() or post() meth ...

Inquiries regarding the use of callback functions in Jquery for ajax requests

Take a look at this code snippet: $("#someid").autocomplete({ source: function (req, resp) { $.ajax({ url: "/api/someapi", type: "GET", dataType: "json", data: { id: req.someid }, b ...

Sorting in reverse order within a table

Is there a way to reverse the order in which my function renders table rows with incremental id? (first row with id=n, last with 1) Here is the code snippet I am using: renderRows = () => { const { receipts } = this.props const reversedReceipt ...

What is the best way to retrieve data obtained through a node module and incorporate it into my HTML code within NodeWebkit?

I've been working on developing an app with NodeWebkit and utilizing the node-phantom-simple module for content scraping. While I have successfully scraped content from a website, I'm now wondering how I can access this data on the HTML side with ...

The string in the text remains unchanged

Currently, I am attempting to replace specific strings as text is entered into the input field. The strings in question are {b} and {\b}. However, I have noticed that not all instances of these strings are being replaced, leaving some behind. Below is ...

Place a call directly from the webpage

Is there a way to initiate a phone call using JavaScript? I've tried the code below: document.location.href = "tel:15555551212" While this code takes me to the dial screen of the mobile application, I actually want to place the call directly. Any ...

Issues with executing javascript callback functions within Node.js and express

/* Access home page */ router.get('/home/', function(req, res, next) { var code = req.query.code; req.SC.authorize(code, function(err, accessToken) { if ( err ) { throw err; } else { req.session.oauth_token = accessToken ...

Determine whether to create or update with a Node.js API

I have developed a nodejs API where users can add new entries by sending a POST request. If the entry already exists, it should be updated. However, I am facing an issue with the findOne() method from mongoose not triggering the update function as expecte ...

Is it possible to load the content before loading the corresponding images?

With a list of 10 contacts to display, I want the contacts to load first so users can view the information before the corresponding images. The HTML structure is as follows: <table id="contactsTable" data-role="listview" data-dividertheme="c"> < ...

Utilizing AJAX requests in PHP's MVC framework

I am currently working on a game site using a combination of php and javascript. All my classes and data are stored in php and then encoded into json format. The view calls a javascript file which, through an ajax request, retrieves the php data encoded in ...

Node.js is having trouble locating the installed MySQL module

I've been attempting to install the mysql module for nodejs using npm on the Windows Subsystem for Linux. After running: sudo npm install -g mysql The console output I received was: + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Tips for sending a PHP JSON array to a JavaScript function using the onclick event

I am trying to pass a PHP JSON array into a JavaScript function when an onclick event occurs. Here is the structure of the PHP array before being encoded as JSON: Array ( [group_id] => 307378872724184 [cir_id] => 221 ) After encoding the a ...

Vue.js - The table updates successfully, however, the data for the selected checkboxes remains unchanged

Encountered a persistent bug that is giving me some trouble. I have a table with rows that can be selected, and when a checkbox is checked, the total amount in the column should be calculated. However, whenever there is a change in the table data through ...