The function in an AngularJS controller is failing to execute

I am experiencing an issue with calling the checkLogin function of a controller. The value returned by checkLogin is used to show/hide elements with ng-show. However, when debugging, I noticed that the execution stops after the function call and does not proceed to execute the function itself. This results in me not receiving any return value. Please review the following code snippet and let me know if you spot any errors.

The function I am trying to call is checkLogin() from the LoginController. Please take a look at that function.

Angular Module:

'use strict';

var mainApp = angular.module('MainModule',['ngRoute']);
mainApp.constant('encrypt', '');
mainApp.config(function($routeProvider){
$routeProvider.when("/",{
    templateUrl: "index.html",
    controller: 'LoginController'
})
.when("/loginpage",{
    templateUrl: "ataclient/login/loginpage.html",
    controller: 'LoginController'})
.when("/registration",{
    templateUrl: "ataclient/register/register.html",
    controller: 'RegistrationController'
});
});

Angular Controller:

'use strict';

function LoginController(encrypt, $http, $scope, $location){

$scope.userName = "";
$scope.password = "";
$scope.loginstatus = true;
$scope.data = "";

$scope.loginSubmit = function(){
    alert("inside login submit");
    if($scope.userName && $scope.password){ 
        $http({
            url: 'http://localhost:8080/com/rest/user/login',
            method: "POST",
            headers:{
                'Content-Type':'application/json'
            },
            data : {
                "userName" : $scope.userName,
                "passwd" : $scope.password
            }
        }).then(function(response){
            $scope.data = response;
        });
        
        if($scope.data.data.encryptedkey != null ){
            encrypt = $scope.data.data.encryptedkey ;
            $scope.loginstatus = false;
            console.log($scope.loginstatus);
            alert(encrypt);
        }
    }
};

$scope.checkLogin = function(){
    alert("inside checkLogin");
    if(encrypt != null){
        return false;
    } else {
        return true;
    }
};

this.login = function(){
    alert("for u in sss");
    $http({
        url: 'http://localhost:8080/com/browsers',
        method: "GET",
        headers:{
            'Content-Type': 'application/json',
            'SessionId': 1478785782179
        }
    }).then(function(Response){
        $scope.data = Response;
    });
};
}

LoginController.$inject = ['encrypt','$http','$scope','$location'];

mainApp.controller('LoginController', LoginController);

Below is the HTML code snippet where the mentioned functions are being called: HTML Piece

<form ng-submit="loginSubmit()" ng-controller="LoginController">

    <div class="col-md-12 col-lg-12 col-xl-12 text-center" id="logintitle">Login Here</div>

    <div class="col-md-offset-2 col-md-8 col-md-offset-2 col-lg-offset-2 col-lg-8 col-lg-offset-2 col-xl-offset-2 col-xl-8 col-xl-offset-2 form-group">
        <label for="UserName"> User Name</label>
        <input type="UserName" ng-model="userName" placeholder="Enter UserName" class="form-control" id="username" aria-describedby="UserNamehelp">
    </div>
    
    <div class="col-md-offset-2 col-md-8 col-md-offset-2 col-lg-offset-2 col-lg-8 col-lg-offset-2 col-xl-offset-2 col-xl-8 col-xl-offset-2 form-group">
        <label for="Password"> Password</label>
        <input type="password" ng-model="password" placeholder="Enter Password" class="form-control" id="password" aria-describedby="PassWordHelp">
    </div>
    
    <div class="col-md-offset-2 col-md-4 col-lg-offset-2 col-lg-4 col-xl-offset-2 col-xl-4">
        <button ng-show ="checkLogin()" type="submit" class="btn btn-primary" id="submit">Submit {{data.data.encryptedkey}}</button>
    </div>
    
    <div class="col-md-4 col-md-offset-2 col-lg-4 col-lg-offset-2 col-xl-4 col-xl-offset-2 ">
        <button type="submit" class="btn btn-primary" id="forgot">Forgot</button>
    </div>

</form>

Answer №1

Make sure to monitor your javascript console for any errors. Replace instances of alert() and console.log() with $log.debug().

The issue in your code seems to be on this line:

if($scope.data.data.encryptedkey != null ){

Since this line is not within the success handler for

$http</cod>, it will execute immediately before anything is assigned to <code>$scope.data
. This will result in an error when trying to access "".data.encryptedkey. Additionally, you are not utilizing the assignment to $scope.data when the data arrives.

Moving the if statement inside the success function and including a failure handler should resolve this issue.

$http({
    url:'http://localhost:8080/com/rest/user/login',
    method:"POST",
    headers:{
        'Content-Type':'application/json'
    },
    data : {
        "userName" : $scope.userName,
        "passwd" : $scope.password
    }
}).then(successFn);

function successFn (response){
    $scope.data = response;
    if($scope.data.data.encryptedkey != null ){
         encrypt = $scope.data.data.encryptedkey ;
         $scope.loginstatus = false;
    }
}

The checkLogin() function is called by Angular only when there are changes. It should be triggered once upon completion of the $http request. However, since the code doesn't set encrypt at that point, the function returns false. To optimize performance, consider setting a flag in the model and checking it directly in the HTML instead of calling a function each time. Minimize directive function calls as they are executed whenever a change occurs.

Answer №2

Setting a value for the constant provider encrypt

mainApp.constant('encrypt','');
...
if($scope.data.data.encryptedkey != null ){
  encrypt = $scope.data.data.encryptedkey;
...

The constant provider should ideally not be altered, consider using the value provider instead.

Your main issue, as pointed out by Duncan, is that your if statement is placed outside of your http response block

...
}).then(function(response){$scope.data = response;});
  if($scope.data.data.encryptedkey != null ){  //<--- issue!
     encrypt = $scope.data.data.encryptedkey;
...

To resolve this, adjust your code as follows to move towards success~~

...
}).then(function(response){
  $scope.data = response;});
  if($scope.data.data.encryptedkey != null ){
     encrypt = $scope.data.data.encryptedkey;
     $scope.loginstatus = false;
     console.log($scope.loginstatus);
     alert(encrypt);
  }
});
...

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

What are the various ways to display time zone in a different format?

I need to display the timezone in a unique manner. I have captured the user's timezone in a variable called timeZone, which currently returns the value as Asia/Calcutta. console.log(timeZone) // "Asia/Calcutta" Is there a way to showcase the timezon ...

Using Javascript to efficiently remove elements with AJAX

Currently, I am learning the basics of HTML and focusing on tasks such as login/logout functionality, creating users, and deleting users (only permitted when logged in as an admin). For updating a user password, I have utilized PUT, for creating a user ac ...

Is it possible to identify users using an iPhone while they are utilizing "Private Browsing" mode?

Looking for a solution to detect private browsing mode in my jquerymobile App. I need localStorage and sessionstorage to work properly, but prompting users to enable cookies when private browsing is enabled doesn't solve the issue. Is there a way to t ...

Updating visual appearance with button clicks and unclicks

Is there a way to dynamically update the button image while clicking on it? This is what I have tried: $('.gamebox_minimap_plus').click(function() { $(this).css("background-image","url('gfx/plus2.png')"); }); The image ch ...

Having a quandary with Socket.io when using clients.length (where clients refers to io.sockets.clients();)

Typically, when sending JSON from one client to another, everything works smoothly. However, if there is only one client, packets are still being sent. To address this issue (on the server-side in node.js), I implemented the following solution: var client ...

Shifting the position of personalized tabs using Jquery

I have created some basic HTML/CSS tabs and I want to move to the next tab by clicking a link at the bottom of every tab. HTML <ul class="tabs"> <li class="active"> <a href="#">Explainer (2mins)</a> <div class=" ...

Navigate to a new tab using this.router.navigate

Is there a way to redirect the user to a specific page with ${id} opening in a new tab, after clicking a button in an angular material dialog box? I want to leave the dialog box open while querying the new page. Currently, the redirect happens but not in a ...

Attempting to bind an input parameter using NgStyle in Angular version 2 and above

Issue: I am in need of a single component (spacer) with a width of 100% and a customizable height that can be specified wherever it is used in the HTML (specifically in home.html for testing): number 1 <spacer height="'200px'"></spa ...

Can one transition from using a callback to a returning Promise in order to implement an ErrorFirstCallback strategy?

In Node.js documentation, it is explained that an ErrorFirstCallback is triggered when the referred function fails. Error-first-callbacks in Node.js I have been practicing with this callback pattern and I am curious to know if it is possible to refactor i ...

Ionic - Retrieve data from a Universal Resource Identifier

When using my application, users have the option to select and crop images using Ionic Native - Crop. Once they have cropped their image, I will receive the URI of the image, for example: file:///storage/emulated/0/Android/data/com.myApp/cache/15353694789 ...

Encountering a JavaScript error due to an erroneous character when trying to parse

I need to convert a `json` string into an object format that is extracted from a `.js` file. Here is the `JSON` string located in `document.js`: [ { "type": "TableShape", "id": "63c0f27a-716e-804c-6873-cd99b945b63f", "x": 80, ...

Transform a javascript object with class attributes into a simple object while keeping the methods

I am seeking a way to convert an instance of a class into a plain object, while retaining both methods and inherited properties. Here is an example scenario: class Human { height: number; weight: number; constructor() { this.height = 1 ...

Why is my DELETE request in AngularJS being sent as an Options request?

Everything was running smoothly until I took a break from this project. Recently, when I try to send a delete request to my server, I encounter the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ...

Storing the Outcome of a mongodb Search in a Variable

I'm encountering an issue where the result of a MongoDB find operation is not being assigned to a variable (specifically, the line var user = db.collection("Users").findOne below), and instead remains undefined. I am aware that the find function retur ...

limitations on passing url parameters in react.js

Currently, I am facing an issue with passing URL parameters in my React.js web app. For illustration purposes, here is a snippet of the routes: import React from "react"; import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom'; ...

Combining strings within a string after a specific word with nested Concatenation

In a given string variable "str," I am looking to concatenate another string between "InsertAfterMe" and "InsertBeforeMe". str="This is a string InsertAfterMe InsertBeforeMe" s1="sometext" s2="soMoreText" aList=[1,2,3,4,5] The concatenated string shoul ...

Allowing a certain amount of time to pass before executing a method

I'm familiar with using setTimeout and setInterval to delay the execution of a method, but I am facing a specific issue. I am working on implementing a card game where three CPU players take turns with a 500ms delay between each turn. Below is the cod ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

Unit testing in JavaScript has its limitations, one of which is the inability to verify if a

Currently, I am working with an Angular application that includes a simple directive called animate. My goal is to use Jasmine to verify if the slideDown method is being called. Below is the current setup of my directive: animateDirective var animate = f ...

What are some best practices for utilizing `element.offsetParent` in HTML SVG elements?

I'm currently updating some JavaScript code that relies on the .offsetParent property. The recent changes in the application involve the use of SVG elements, which are causing issues with the JavaScript as mySvgElement.offsetParent always returns unde ...