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

What is the best way to store the outcome of a promise in a variable within a TypeScript constructor?

Is it possible to store the result of a promise in a variable within the constructor using Typescript? I'm working with AdonisJS to retrieve data from the database, but the process involves using promises. How do I assign the result to a variable? T ...

An issue occurred while attempting to execute a function in AngularJS

Currently, I am in the process of developing a cross-platform application using AngularJS, Monaca, and Onsen UI. My current challenge involves calling a function in my controller from an ng-click() event on my view. However, upon clicking the button that ...

What are the necessary headers that must accompany a post request?

While testing the server with Postman, everything seems to be working fine as I receive a response: https://i.stack.imgur.com/yMRfj.png However, when attempting to make a POST request from the browser using the same address, it results in an error and th ...

Looking for guidance on writing a JASMINE test case for my method. I've been struggling to mock the event listener. Can you please direct me to a relevant link or share some mock examples

Looking to create a jasmine test for the code snippet below... refreshCacheIfNewVersionIsAvailable(); //Function to check for a new cache version on page load and refresh the app cache if newer files are available function refreshCacheIfNewVersionIsAvail ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

Taking out the z-index from the transition code

Is there a way to restructure the code without needing to use z-index for the transition? Without z-index: https://jsfiddle.net/Legcb42d/ .container1 { position: relative; width: 100%; height: 100%; } .container1.slide { height: auto; min-heigh ...

Separating express routes into individual files

After trying multiple solutions from Stack Overflow and various patterns for organizing routes in Node.js, I still can't seem to get it right. The endpoint either throws errors or returns a 404. Despite following suggestions from different sources lik ...

Which is better for your website: SSG vs SSR?

Currently, I am diving into Nextjs and constructing a website using this framework. The site includes both public pages, protected routes (like user dashboard, user project details, and general user data), as well as product pages. I have been pondering h ...

AngularJS: dynamic autocomplete field with scroll functionality

This is my HTML code: <div class="form-group"> <label class='control-label col-md-4' for='id_paymentCurrency'>{{'PAYMENT_CURRENCY' | translate}}</label> <div class='col-md-4'> ...

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

Executing a JS function within a table cell

I've been attempting to invoke a function within a table cell to dynamically create some data, but I keep encountering this error below. I'm uncertain whether I'm correctly calling defined functions and JavaScript functions inside the table ...

Utilizing JQuery to modify the element's id and trigger a function upon clicking

There is an element with a specific ID that I have changed. However, even after changing the ID and clicking on the element with the new ID, it still triggers the function associated with the old ID. $('#1st').click(function(){ $('#1s ...

How can I prevent the same JavaScript from loading twice in PHP, JavaScript, and HTML when using `<script>'?

Is there a PHP equivalent of require_once or include_once for JavaScript within the <script> tag? While I understand that <script> is part of HTML, I'm curious if such functionality exists in either PHP or HTML. I am looking to avoid load ...

Is React.js susceptible to XSS attacks through href attributes?

When user-generated links in an href tag appear as: javascript:(() => {alert('MALICIOUS CODE running on your browser')})(); This code was injected via an input field on a page that neglects to verify if URLs begin with http / https. Subseque ...

Retrieve and display the number of items in the shopping cart directly from localStorage using React

Utilizing react along with globalContext to populate a cart page by adding items that are then stored in an array within localStorage results in the following data structure being created: 0: {id: "9", title: "Apple Watch SE 40mm (GPS) - Spa ...

Using an AngularJS directive to modify CSS styles

I'm attempting to modify DOM CSS styles using Angular. If the textbox value is set as the height, I have assigned ng-model to the textbox and then ng-style="{height:heightdef}" How can I achieve this using a directive? Fiddle :: http://jsfiddle.n ...

Issue: The keyword in React/React-Native is returning a boolean value instead of the expected element object

I've recently delved into learning and coding with React, and I'm encountering a bug that I need help fixing. The issue lies within my application screen where I have two checkboxes that should function like radio buttons. This means that when on ...

Navigating through the img src using JavaScript

Currently, I am working on a task that involves the following code snippet: <input type="file" id="uploadImage" name="image" /> <input type="submit" id="ImageName" name="submit" value="Submit"> My goal is to have the path of the selected imag ...

AngularJS date formatting fails to properly format dates

{{ map.thedate }} The result is 2014-06-29 16:43:48 Even after using the following code, it still displays the same date as above. {{ map.thedate | date:'medium' }} ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...