Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs

var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope','$rootScope', '$http',
function($scope,$rootScope, $http) {
    $scope.loginurl = 'loginsubmit.php';
    $scope.loginFormSubmit  = function(isValid) {           
        if (isValid) {

            $http.post($scope.loginurl, {"username": $scope.username,"password": $scope.password}).
                    success(function(data, status) {
                        $scope.status = status;
                        $scope.data = data;
                        $scope.isAdmin=data.isAdmin;
                        $scope.username=data.username;
                        location.href="Index.html";                         
                    })  
        } else {

              alert('Form is not valid');
        }

    }
 
 html form code

 <div class="row" ng-app="formExample" >
       <div ng-controller="formCtrl">
          <div class"col-md-8">&nbsp;</div>
          <div>username: {{$scope.username}} </div>

Answer №1

When it comes to login and authentication, I follow a similar approach to Marco (as mentioned in his comment) by storing user information in $rootScope. However, I am cautious about overloading the $rootScope with unnecessary data.

To demonstrate this concept, I have created a simple jsfiddle playground inspired by an article I came across:

$rootScope-and-$scope.html

http://jsfiddle.net/chrislewispac/kd8v6thm/

var app = angular.module('myApp', []);

 app.controller('Ctrl1', function ($scope, $rootScope) {
 $scope.msg = 'World';
 $rootScope.name = 'AngularJS';
 });

 app.controller('Ctrl2', function ($scope, $rootScope) {
 $scope.msg = 'Dot Net Tricks';
 $scope.myName = $rootScope.name;
 });

I appreciate all the insightful answers and comments provided. As a learning tool, I recommend playing around with the provided fiddle to gain a better understanding. Personally, experimenting with small snippets of code in isolated environments has helped me learn and troubleshoot effectively.

UPDATE: Exploring alternative methods of data sharing across controllers in Angular:

In addition to utilizing $rootScope, creating an auth 'factory' is another efficient way to share data between controllers without relying on a database. Services and Factories serve as effective tools for facilitating data exchange among controllers, which aligns with best practices.

A comprehensive discussion on this topic (and others) can be found here: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

For a practical example featuring a service, please refer to the updated fiddle:

http://jsfiddle.net/chrislewispac/kd8v6thm/1/

Here is the additional content showcasing the implementation of a service:

app.service("auth", [ function () {
return {
    getAuth: function () {
        var info = {
            name: "Name",
            password: "Password"
            }
        return info;
        }
    };
}]);

Answer №2

To prevent losing the scope, consider setting a timeout on your location.href.

Prior to redirecting, there are various ways to ensure your user data is accessible throughout the app. You can store the user variables in a controller that impacts all views (such as a controller in app.js), or store them in $rootScope or localStorage/sessionStorage as recommended by @Marco in the comments.

Additionally, use {{ username }} instead of {{ $scope.username }}. The former will display the username while the latter will not output anything.

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

Struggling to get Canvas2ImagePlugin to function properly within an Ionic app and Angular.js

Recently, I stumbled upon a plugin that allows me to save images in my App, a solution I have been struggling to find. My question is: how do I integrate this into an angular framework? As a newcomer to angular.js, I'm feeling quite lost. The code sni ...

Problem with Angular: ng-show not constantly re-evaluating expression

Utilizing a variable named activeScope to manage the state and toggle between two forms. This variable updates its value when a tab is clicked, triggering changeScope. While the change in active states for the tab buttons registers correctly, the divs for ...

What strategies can I implement to prevent the JavaScript CallStack from becoming overloaded?

The code snippet below outlines the functionality achieved through JavaScript (specifically for a node.js COMET application): A request is sent to the server and held until there is a response. Upon receiving a response, the data is processed, and anothe ...

Retrieve a file from an Express API using React with the help of Axios

When working with a React client and an Express API, how can the React client download a file sent by the Express API? Issue: If I manually enter the URL into my browser's address bar and hit enter, the file downloads successfully. However, when I ...

Is it possible to run a Universal Windows Platform desktop app on an Android mobile device?

After successfully developing a Universal Windows Platform app in Visual Studio using WinJS, JavaScript, CSS and HTML, I am now interested in leveraging the same code base to create an Android application. Could you guide me on the necessary steps to run ...

Exploring Checkbox Limiting with jQuery

Is there a more efficient approach to restrict the selection of checkboxes? I want the script to be adaptable depending on the applied class, which will always indicate the maximum allowed value (e.g., "limit_1" or "limit_2"). Currently, I'm creatin ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

The attribute 'positive_rule' is not found within the structure '{ addMore(): void; remove(index: any): void;'

data() { return { positive_rule: [ { positive_rule: "", }, ], }; }, methods: { addMore() { this.positive_rule.push({ positive_rule: "", }); }, ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: My rendered page: I have included the angular- ...

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

Utilizing Ajax for dynamic PHP result determination

HTML CODE <div class="card text-center pricing-card mb-20"> <ul class="list-group list-group-flush"> <?php $gbewas = mysqli_query($con,"SELECT * FROM price"); while($okks = mysqli_fetch_array($gbewas)) { ?> <li cla ...

Checking a bcrypt-encrypted password in an Express application

I am encountering an issue with my login password verification code. Even when the correct password is entered, it is not being validated properly. Can anyone provide assistance with this problem? login(req, res) { const { email, pass } = req.body; ...

Exploring CountUp functionality with Vue framework

I'm still getting the hang of Vue and recently completed my first project following a tutorial. This project is my first solo endeavor. Currently, I am working on a basic page to display the scores between two teams. The scores are retrieved from an ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Encountering a Django Channels issue while loading the JavaScript wrapper

After successfully running the server, the following appeared in my cmd prompt: System check identified no issues (0 silenced). January 21, 2020 - 17:43:42 Django version 3.0.2, using settings 'crm.settings' Starting ASGI/Channels version 2.4.0 ...

Effortlessly sending multiple forms on a single page via POST in Express JS without the need for page refresh

I am creating a new application using ExpressJS and I want to include the following HTML code in a jade file. On one of my pages, I have 4 form buttons: <div class="dog"> <div class="dog_wrapper clearfix"> <div cla ...

obtain direct access to the $scope variable when using ng-if

Is there a more effective way to access scope created by ng-if in my directive without using $parent.params.text? <span ng-if="params" uib-tooltip="{{params.text}}"></span> .directive('myDirective', functions(){ return { te ...

What is the method for eliminating quotes from a URL?

Changing the URL: history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14="'+urldates+'"&usp-custom-8="'+title+'"'); After making changes, it s ...