Retrieving information from one controller to another controller

I have been tasked with developing an application using angularjs. The application consists of a login page and home page.
The layout is divided into two sections - header and container, each controlled by headerCtrl and loginCtrl respectively. The header remains constant throughout both sections, only the content changes after logging in.

This is the loginCtrl code:

    angular.module('app').controller('LoginCtrl', ['$scope', 'LoginService',
    function($scope, LoginService) {
        $scope.title = "Login";

        $scope.login = function() {
            var user = {
                username: $scope.username,
                password: $scope.password
            };
            LoginService(user);
        };

    }
]);

This is the loginService code:

angular.module('app')
.factory('LoginService', function($http, $location, $rootScope) {
    return function(user) {
        $http.post('/login',{
                username: user.username,
                password: user.password
            }).then(function(response) {
            if (response.data.success) {
                console.log(response.data);
                $rootScope.user = response.data.user;
                $location.url('/');
            } else {
                console.log(response.data.errorMessage);
                $location.url('/');
            }
        });
    };
});

This is the header.html template:

<div ng-controller="headerCtrl" class="container-fulid">
    <div class="row custom-row1">
        <div><span class="title_top pull-right">{{ user }}</span></div>
    </div>
</div>

I need guidance on how to implement headerCtrl and modify the login controller and service to access user details (username) in the header.html file.

Answer №1

Here is some assistance for you:

Your provided HTML code snippet:

<div ng-controller="loginCtrl" class="container-fulid">
    <div class="row custom-row1">
        <div><span class="title_top pull-right">{{ title }}</span></div>
    </div>
</div>

Your AngularJs code example:

var baseURL = "http://localhost:56110/";
var app = angular.module('loginApp', []);

app.service('loginService', function ($http) {
    this.login = function (user) {
        return $http.post('/login', user)
          .success(function (data, status, headers, config) {              
           })
           .error(function (data, status, headers, config) {               
           });
          }
        });
    };
});

app.controller('loginCtrl', function ($scope, loginService) {

    $scope.title = "Login";
    $scope.uid = 123;
    $scope.pwd = 123;

    $scope.login = function () {
        var pwd = {
            username: $scope.uid,
            password: $scope.pwd
        };

        loginService.login(pwd).then(function (response) {               
            if (response.data.success) {
                console.log(response.data);
                $rootScope.user = response.data.user;
                $location.url('/');
            }
            else {
                console.log(response.data.errorMessage);
                $location.url('/');
            }
        });
    };
});

Answer №2

One way to communicate between the login controller and header controller is by using a broadcast on the $rootScope. Once the login service has finished, emit an event with the user details that can be listened for in the header controller.

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

Adding additional information to the HTML5 doctype is indeed achievable

Imagine you have a set of IE conditional comment tags in the beginning of your HTML document: <!--[if IE 6]><html class="no-js ie6" lang="en" ><![endif]--> <!--[if IE 7]><html class="no-js ie7" lang="en" ><!--<![endif]- ...

What is the best way to continuously add strings to an existing string within a loop?

When attempting the code below, I am receiving an empty string as output. var jsObj2 = { "key1": "value3", "key4": "value4" }; var c = ''; for (var key in jsObj2) { c.concat(key + ': ' + js ...

What is the correct way to invoke a function from an external JavaScript file using TypeScript?

We are currently experimenting with incorporating Typescript and Webpack into our existing AngularJS project. While I have managed to generate the webpack bundle, we are facing an issue at runtime where the program is unable to locate certain functions in ...

"The utilization of either Threejs ArrowHelper or Line with an outlined design

Is there a way to outline an arrow or line using the ArrowHelper or Line geometries within the Three.js framework? While trying to achieve this, I encountered the issue that outlining a complex object or a line is not as straightforward as shown in this e ...

What is the method to display HTML code using JavaScript within a span element in a JSP page?

While working on a jsp file, I came across a span tag with the following code: <span id="divBasicSearchResults" style="height:100%;"></span> Below is the Javascript function that generates HTML content for this span: function renderBasicSear ...

Tips for ensuring the server only responds after receiving a message from the client in a UDP Pinger system using sockets

I am in the process of developing a UDP pinger application. The objective is for the client to send a message (Ping) and receive pong back 10 times. However, the challenge lies in sending the messages one at a time instead of all together simultaneously. T ...

Updating the value of a key within a jQuery object

A custom modal plugin has been developed with options that can be set by default or by the user. These values are passed to a function for updating, and it is desired that the options object as a whole is updated rather than individual values. The user&ap ...

Using a nested for loop within a React render function

Despite the site suggesting that there are many similar questions, I haven't been able to find the specific answer I'm looking for. I believe this should be an easy task for React pros, but as a beginner, I'm struggling. Currently, I have t ...

Express NodeJS encountering issues with partials

I am currently experimenting with using partials in my ExpressNodeJS project. My Node version is 3.x. This is the structure of my project directory: D:\eclipse\workspace\test I have created a sub-folder and added headModule.ejs in the vi ...

What could be causing the RTCPeerConnection icegatheringstatechange to not function properly?

I have been trying to utilize the icegatheringstatechange event handler, but it doesn't seem to be functioning properly. Is there a different method I can use to monitor changes in icegatheringstate? How can I determine when all ice candidates have be ...

The mistake is indicating the npm title of a package that is not present

https://i.sstatic.net/5bywN.png An issue has arisen - the module cannot be found, even though such a module does not actually exist. The correct module name should be babel-plugin-proposal-class-properties (and the error is showing as 'babel-plugin-t ...

Importing a .glb file in three.js results in a darkened object being

Whenever I import a .glb file in threejs, it displays a black object on the surface. Setup = (scene, camera, renderer) =>{ this.scene = scene const objLoader = new GLTFLoader(); objLoader.load('chair.glb', (gltf) => { le ...

AngularJS enables the loading of directives dynamically, but sometimes encounters errors such as "Restricted URI access denied."

Presently, I am in the process of developing a small educational project using HTML5, CSS, JS and AngularJS. Hiccup: Loading an AngularJS Directive in my index.html file Error code [1] - Local browser Error: Access to restricted URI denied Various resp ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

Form Validation in JavaScript Continues to Submit Form Even When 'False' is Detected

Here is the issue at hand - I am restricted to using older browsers (IE8 and FF8) by corporate policy. Despite my research indicating otherwise, it seems like this might be the root cause of my troubles. My current setup includes PHP 5.5.12 on Apache 2.4. ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

Unable to style Backbone View with CSS

Recently started diving into the world of Backbone, and it seems like I might be missing a key concept here. In my View object, there's a snippet of code that's puzzling me... First off, I can't figure out why the CSS change in the highli ...

Utilize multiple classes in inline styling within HTML

I'm trying to dynamically apply the "more" CSS class directly to an inline style tag, but I haven't had success with my current approach. Unfortunately, in my situation, I can't create a class. The method is working for <p> tags but no ...

When dealing with back-end data in JavaScript, converting long types can result in a

When parsing data of the Object type in C#, utilizing JavaScript on the front end to parse the data can result in loss of precision. <!DOCTYPE html> <html> <head> <title>Example using BigNumber.js</title> <script s ...

The jQuery method .index() can be quite perplexing when it comes to

http://learn.jquery.com/using-jquery-core/understanding-index/ After reading the article linked above, I found myself struggling to grasp the reasoning behind why the index number changes in a peculiar manner when an argument is used with .index(). Consi ...