retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file:


app.controller("logincont", ['$scope','$http','md5','$window','$rootScope',function($scope,$http,md5,$window,$rootScope){
     $scope.$watch('pass', function(val) {
          $scope.password = md5.createHash($scope.pass || '');
        });
    $scope.cari = function () {
            $http.get('http://localhost:8089/MonitoringAPI/webresources/login?a='+$scope.userid+'&d='+$scope.password).then(function(response){
           $scope.reslogin  = response.data;
           $rootScope.reslogin2 = response.data[0].username;
           $scope.reslogin3 = response.data[0].lsmenu[0].idmenu; 
           console.log($scope.reslogin);
           console.log($scope.reslogin2);
      });
          };   
}]);


app.controller("moncont", ['$scope','$http','$filter','$rootScope',function($scope,$http,$filter,$rootScope){
      $scope.user = $rootScope.reslogin2;
      console.log($scope.user);
}]);

Want the content of

<p>Username : {{user}}</p>
to display properly.

Answer №1

Ensure that a value is properly assigned before attempting to access it. Within the moncont controller, monitor $rootScope.reslogin2 and assign its value to $scope.user in the watch function.

Answer №2

user from moncont module not in sync with the desired value. To resolve this issue, instead of assigning

$scope.user = $rootScope.reslogin2;
, you can define a getter using Object.defineProperty:

angular.module('app', [])
  .controller('logincont', function($rootScope, $scope, $timeout) {
    $scope.cari = function() {
      $timeout(function() {
        $rootScope.reslogin2 = ($rootScope.reslogin2 || 0) + 1;
      }, 1000)
    }
  })
  .controller('moncont', function($rootScope, $scope) {
    Object.defineProperty($scope, "user", {
      get: function() {
        return $rootScope.reslogin2
      }
    });
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app'>
  <div ng-controller='logincont'>
    <button ng-click='cari()'>Cari</button>
  </div>
  <div ng-controller='moncont'>
    user: {{user}}
  </div>
</div>

Answer №3

To implement this functionality, insert the provided method into your controller.

$scope.initialize = function(){
   $scope.user = $rootScope.reslogin2;
   console.log($scope.user);
}

Your HTML template should resemble the following:

<div ng-controller="moncont" ng-init="initialize()">
    <p>User: {{user}}</p>
</div>

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

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...

Remove the post by utilizing the $.ajax function

I am just starting out with using $.ajax and I'm not very familiar with it. I have a button that is meant to delete a user post based on the article ID provided. <button type="button" onclick="submitdata();">Delete</button> When this but ...

Unable to bind Firebase snapshot.val() to $scope variable

Utilizing FireBase, I am attempting to perform queries where data is logging in successfully, but not appearing visually within the HTML $scope. var shopRef = firebaseDataService.intro; $scope.shops = []; var taskRef = shopRef.orderByChild("cat").equalT ...

Unable to retrieve req.files using multer from the req object

I have been attempting to send a file to the server using a NodeJs script. Below are the steps I am taking. HTML <md-tab label="Upload log"> <md-content class="md-padding" id="popupContainer" ng-cloak> <h4>Send a zip file< ...

Encountering an "XML Parsing Error: no element found Location" error in AngularJS $http when JSON results are expected on a GET request

Whenever I try to make an angularjs $http GET request, I am faced with an XML parsing issue. Here is the code snippet for the $http call: $http({ method: 'GET', url: "myapp/api/items" + itemId }); The error message I receive is as fol ...

What are some of the potential drawbacks of utilizing the same template ref values repeatedly in Vue 3?

Is it problematic to have duplicate template ref values, such as ref="foo", for the same type but different instances of a component across views in a Vue 3 application? Let's consider the following example pseudocode: // ROUTE A <te ...

Store various dropdown selections in an array

Questions are being generated from a database for users to answer using a drop-down menu. Upon selecting a specific option, a suggestion is added to an array triggering a JavaScript on-change event. Once all questions are answered, the array including all ...

Ways to retrieve the innerHTML of a Script Tag

After spending what feels like an eternity searching, I still can't figure out how to get the innerHTML of a script tag. Here's where I'm at... <script type="text/javascript" src="http://www.google.com" id="externalScript"></script ...

Looking for the optimal method to display numerous lines of text in HTML, one by one, at intervals of 60 seconds?

I'm working on a display page for my website. The main text in the center needs to change every 60 seconds. I have over 150 individual lines of text that I want to cycle through on the page. What would be the most efficient way to load all these te ...

Arrange objects on a grid

I've got an array filled with objects, each containing 3 images, a name, and some details. I'm attempting to display these objects on Bootstrap cards, but currently each card is showing up on its own line. My goal is to arrange the cards in a gri ...

How about: "Using Node.js and Express to declaratively define a route for

I am facing an issue managing my routes in declarative objects and initializing/registering the endpoint handlers using one or more of these objects. The problem arises when I attempt to register the handlers in a loop of the declarative routes, methods, ...

Using AngularJS, REST API, SpringSecurity, and Hibernate in any software program

I am looking to create a web application using the following technologies: AngularJS, Spring Security, RestAPI, Hibernate Can anyone recommend or provide code for integrating these technologies together? ...

Developing a Link Element in Angular 2

Exploring the creation of a wrapper component in Angular 2, inspired by tools like react-bootstrap. The goal is to avoid repeating the component structure each time and instead create a reusable component. The desired reusable component should have a stru ...

Incorporating a transparent icon onto an HTML background

I'm struggling to place a transparent white envelope icon on a green background. I don't understand why it's not working, especially when the telephone icon worked fine. Side Question.: Any recommendations for how to add something above the ...

Step-by-step guide to retrieving the value of a duplicate input field with identical IDs in Angular4

This is the form I am working on: <button (click)="M_add()">Add</button> <tbody id="_tbody"> </tbody> Whenever the add button is clicked, it triggers the creation of an input field. let tbody = document.getElementById("_tbody"); ...

JavaScript believes that the function is not defined, despite its clear existence

This question pertains to an issue regarding the recognition of Bookshelf.js model function as a function. The error message "Function is undefined, Bookshelf.js model function is not being recognized as a function" arises when trying to POST to the login ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...

Issue with parse-angular-patch no longer functioning

My experience with parse-angular-patch was going great until I found out that parse.com is shutting down in a few months. To continue using the parse SDK with a parse open source server, upgrading the javascript SDK version to 1.9.2 is necessary. Attempti ...

When using VueJS routing with the same component, the OWL Carousel does not get triggered

Hello I am currently experiencing an issue with VueJS rendering images into a Carousel plugin (OwlCarousel) when loading the same component with different variables. When initially loading the page with images, everything functions correctly and the caro ...

Leveraging the power of AngularJS within an ASP.NET MVC architecture, bypassing

Looking to incorporate AngularJS with ASP.NET MVC for my website, while utilizing Active Directory for authentication. ASP.NET MVC seems like the best choice for routing and handling authentication/authorization. My plan is to create a _Layout.cshtml page ...