Controller encountering undefined rootScope in AngularJS

I have developed a basic AngularJS application with two template pages: login.html and content.html. The pages are loaded dynamically into the index.html using ng-view and routing functionalities.

Everything is running smoothly.

Take a look at my index.html below:

<!DOCTYPE html>
<html ng-app="testApp">
<head>
    <title>Test</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-route.js"></script>
    <script src="app.js"></script>
</head>
<body>

    <h1>Test Page</h1>

    <div ng-view></div>

</body>
</html>

Here's the layout for login.html:

<div>
    <input type="text" name="username" id="username">
    <input type="password" name="password" id="password">
    <button ng-click="doLogin()">Submit</button>
</div>

And this is the structure of the content.html:

<div>
    <button ng-click="alertPassword()">Click Me!</button>
</div>

The app.js script contains:

var app = angular.module('testApp', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(false);
    $routeProvider
    .when('/', {
        redirectTo: '/login'
    })
    .when('/login', {
        templateUrl: 'login.html',
        controller: 'loginController'       
    })
    .when('/content', {
        templateUrl: 'content.html',
        controller: 'contentController'
    })
    .otherwise({
        redirectTo: '/'
    })
})
.controller('loginController', function($scope, $rootScope, $location){
    $scope.doLogin = function (password) {
        $rootScope.password = password;
        $location.path('/content');
    }
})
.controller('contentController', function($scope, $rootScope){
    var password = $rootScope.password;
    $scope.alertPassword = function () {
        alert(password);
    }
})

All parts of the application are functioning correctly, except for the fact that the value of $rootScope.password on the content page shows as undefined.

When I click the button labeled Click Me!, I anticipate retrieving the password entered on the login page, but instead receive 'undefined'.

Note: Despite searching extensively on Stack Overflow, no solution has been found for this specific issue.

Answer №1

The reason for the issue is that in your login.html, you are calling the function doLogin without providing any parameter:

<button ng-click="doLogin()">Submit</button>

However, the function doLogin actually requires a password parameter to be passed to it:

$scope.doLogin = function (password) {
    $rootScope.password = password;
    $location.path('/content');
}

As a result, the password property of your $rootScope will remain undefined. To fix this issue, update your login.html with the following code:

<div>
    <input type="text" name="username" id="username">
    <input type="password" name="password" id="password" ng-model="password">
    <button ng-click="doLogin(password)">Submit</button>
</div>

I have added an ng-model attribute to your password input field, which links the input value to a scope variable called password. This variable will then be passed to the doLogin function when the button is clicked.

Answer №2

Make sure to include the password variable in the doLogin() function

Here is an example of how you can do it: HTML

<div>
    <input type="text" name="username" id="username">
    <input type="password" ng-model="password" name="password" id="password">
    <button ng-click="doLogin(password)">Submit</button>
</div>

In your controller

.controller('loginController', function($scope, $rootScope, $location){
    $scope.password = "";
    $scope.doLogin = function (password) {
        $rootScope.password = password;
        $location.path('/content');
    }
})

Answer №3

Here is a different way to approach it:

.controller('loginController', function($scope, $rootScope, $location){
    var userPassword = $rootScope.userPassword; ///// <---
    $scope.handleLogin = function (userPassword) {
        $rootScope.userPassword = userPassword;
        $location.path('/homepage');
    }
})
.controller('contentController', function($scope, $rootScope){
    var password = $rootScope.userPassword;
    $scope.displayUserPassword = function ( ---> password  ) {
        alert(password);
    }
})
  • Avoid writing '--->' for clarity. It's just a marker.

Update your html with the following:

"handleLogin(userPassword)" // <--- include userPassword as an argument.

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

Obtain the jQuery dialog's closure event within the $.Ajax completion function

I have developed a custom jQuery plugin that utilizes jQuery Dialog to showcase messages. Specifically, I am using it within my jQuery $.ajax -->done function. My goal is to capture the close event of the Dialog in the .ajax function so that I can redir ...

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Clearing the ng-model value in a controller following an ng-change event

Is there a way to reset the ng-model value in the controller after an ngChange event without needing to use a directive? <div ng-repeat="i in items"> <!-- Some DOM comes here --> <select ng-model="i.avail" ng-change="changeAvail(i. ...

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

What is the best way to incorporate Ajax into a Rails application?

Check out the Webpage Design I am currently working on a Todo List that includes various Todo Items. Each incomplete task has a button called "Mark Item as Done" next to it, which triggers the button_to method when clicked. I am facing challenges in imple ...

What is the correct way to utilize href in CSS content property?

Below is the content of a box I have: https://i.sstatic.net/QmG5i.png When the above box is hovered over, it flips to this: https://i.sstatic.net/QsS9t.png This block's HTML code is as follows: <div class='tiles'> <div class= ...

What is the process for configuring socket.io to solely listen on a single designated route?

Is there a way to make socket.io listen only on my /home route, instead of every route? I tried changing the configuration but it only displayed a JSON file on the home path. const server = require('http').Server(app); const io = require('s ...

Leverage the Google Drive API for the storage of app-specific data

I'm currently developing a JavaScript application that runs on the client side and need to store a JSON object containing configuration details in a Google Drive Appdata file. Through the Google Drive API, I can successfully check for the file within ...

What is the best way to ensure the checkbox functions correctly in this specific situation?

I am utilizing PHP, Smarty, and jQuery in the development of my website. Currently, I am working on implementing checkboxes within a Smarty template. Below is a snippet of my Smarty code related to checkboxes: <table cellpadding="5" cellspacing="0" bor ...

What determines why the input value is restricted to being of type string?

In my ReactJS component, I am struggling to set the state value as an integer using setState. This is causing issues with the radio button not being checked. constructor(props) { super(props); this.state = { frequency: 1, } handleSelectChange(eve ...

Performing an AJAX call using the PUT method to update information in the

I am facing difficulties when trying to call my REST api from JavaScript, as I keep receiving either a Bad Request or an Unsupported Media Type error depending on my testing... Here is my Servlet code: /** * Update an existing frame * * @ ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Updating the FormArray index using Angular's `removeAt(i)` function does not reflect changes in the DOM

I initially suspected that there was an issue with my implementation, but it appears that the code I used to create a dynamic FormArray should be working, as indicated in this question I posted. However, when I integrate it into my project, the remove func ...

Fixing Half Screen Sidebars

I have a query regarding my coding problem. I am trying to create two pop-ups that occupy half of each screen. As I am new to JavaScript and jQuery, I want to ensure that I am doing it correctly. Is there a way for the left side to slide out from the left ...

What format is recommended for organizing controllers when working with angular-ui-router?

When using angular-ui-router, each state requires its own controller, unlike the previous method where one controller supported multiple router views. For example: $stateProvider .state('posts', { abstract: true, url: '/posts&apos ...

Adjusting Image Size According to Window Resize?

My current issue involves having four images displayed side by side. When the window size is adjusted or viewed on a smaller device, the layout shifts to a line jump (with three images in a row and the fourth one below). What I actually want is for all fou ...

Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected. Here's an example of my code: <div id="outline"></div> And here is t ...

"Utilizing AngularJS: Incorporating multiple ng-views within a single template

While developing a dynamic web application with AngularJS, I came across a question - is it feasible to include multiple ng-view elements within a single template? ...

Elevate your AngularJS directive by incorporating ngModel into an Angular component

Attempting to switch my AngularJS directive over to an Angular Component. Below is the original code for the directive: ng1AppModule.component('ng1Tmp', { bindings: {p: '<'}, require: {ngModel: 'ngModel'} }); Her ...