Is it possible to update the variable value in one controller from another controller after an http.get request has been made

I have encountered an issue with updating a variable from one controller to another using a service. Despite my efforts, the variable is not being updated.

The goal is to have the variable $scope.names in controller 'select' update in controller 'current' and display the updated information.

app.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$http.get('/myapp/stocknames'). 
success(function(data) {
    $scope.names=data;
    myService.names=data;
});
}]);

I am utilizing a service named myService to facilitate the exchange of data between the two controllers. The initialization of the names array within the service is done as follows:

app.service('myService', function($http, $rootScope) {
   this.names=[]
   });

app.controller('current', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.names=myService.names;
console.log($scope.names);  
}]);

I am seeking assistance on how to ensure that the current controller reflects the updated data once the $scope.names variable in the select controller has been updated.

Despite my best efforts, it seems like what I have implemented should work :-/

Answer №1

There are various methods to achieve this:

First: By monitoring the changes in the service variable data

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

app.service('dataService', function() {
  this.serviceData = "test";
});

app.controller('MainCtrl', function($scope, dataService) {
  $scope.mainClickHandler = function(mainData) {
    dataService.serviceData = mainData;
  }
});


app.controller('SubCtrl', function($scope, dataService) {
  $scope.name = 'World';

  $scope.getServiceData = function() {
    return dataService.serviceData;
  }

  $scope.$watch("getServiceData()", function(newValue, oldValue) {
    if (oldValue != newValue) {
      $scope.name = newValue;
    }
  });
});

http://plnkr.co/edit/G1C81qvDD179NILMMxWb

Second:

Using event broadcast

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

app.factory('dataService', function($rootScope) {
  var serviceData = {
    "mydata": "test"
  };

  $rootScope.$watch(function() {
    return serviceData.mydata;
  }, function(newValue, oldValue, scope) {
    $rootScope.$broadcast('dataService:keyChanged', newValue);
  }, true);

  return serviceData;

});

app.controller('MainCtrl', function($scope, dataService) {
  $scope.mainClickHandler = function(mainData) {
    dataService.mydata = mainData;
  }
});


app.controller('SubCtrl', function($scope, $rootScope, dataService) {
  $scope.name = 'World';

  $rootScope.$on('dataService:keyChanged', function currentCityChanged(event, value) {
    console.log('data changed', event, value);
    $scope.name = value;
  });

});

http://plnkr.co/edit/tLsejetcySSyWMukr89u?p=preview

Third:

Using callback

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

app.service('dataService', function() {
  var serviceData = "test";
  var callback = null;
  this.updateServiceData = function(newData){
    serviceData = newData;
    if(null!==callback)
    {
      callback();
    }
  };

  this.getServiceData = function(){
    return serviceData;
  };

  this.regCallback = function(dataCallback){
    callback = dataCallback;
  };
});

app.controller('MainCtrl', function($scope, dataService) {
  $scope.mainClickHandler = function(mainData) {
    dataService.updateServiceData(mainData);
  }
});


app.controller('SubCtrl', function($scope, dataService) {
  $scope.name = 'World';
  $scope.dataChangeCalback = function() {
    $scope.name = dataService.getServiceData();
  }
  dataService.regCallback($scope.dataChangeCalback);
});

http://plnkr.co/edit/vrJM1hqD8KwDCf4NkzJX?p=preview

Answer №2

To achieve this, one approach is to bind the entire service to the scope:

myApp.controller('select', ['$scope', '$http', 'myService', function($scope,$http, myService) {
          $scope.myService = myService;
          $scope.click = function () {
              myService.names = "john";
        };

Subsequently, we can directly modify myService.names within the controller.

The current controller should be structured as follows:

myApp.controller('current', ['$scope', '$http', 'myService', function($scope,$http, myService) {
$scope.names=myService.names;
console.log($scope.names);  

          $scope.$watch(function() { return myService.names; }, function(newVal, oldVal) {
   $scope.names = newVal;
   });
 }]);
}]);

We then utilize a watcher expression.

Alternatively, a watcherExpression can also be used. Refer to for more detailed information.

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

By implementing setInterval, but I aim to deactivate it upon detecting user input

Currently, I have a function being called using setInterval that loads my page via an ajax get request and displays the response in real-time like a live updates page. The issue arises when users are inputting data into the form because the page is refresh ...

Using React to pass a value through state when handling changes

Trying to implement handleChange and handleSubmit methods for a login page in React. Set username and password values in state, update them when form inputs change, then submit using the updated values. However, values print as undefined in the console. N ...

What is the best way to retrieve the total number of nested objects within an object?

I'm trying to figure out how to get the number of nested objects in the object a. a = { firstNested: { name: 'George' } secondNested: { name: 'James' } } I thought about using .length, which is typ ...

Creating dynamic pagination in React using a variable length loop

I'm currently implementing pagination using react ultimate pagination. When a page number is clicked, I update a variable to display the necessary content. The challenge arises from having a loop with a variable number of elements, making it impossibl ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...

Uncover the structure of a regular expression pattern to discover the quantity of tokens and the size of the anticipated matches

I am looking to validate certain fields in my forms by determining the number of tokens and length specified by a particular regular expression. For example, For the pattern [0-9]{3},[0-9]{2}, I need to identify 5 as the length and 2 as the number of to ...

Initiate an animation in Wordpress once the entire page has finished loading

Recently, I incorporated some "raw html" elements with animations into my WordPress site. However, the issue I'm facing is that these animations kick off as soon as the page loads, without waiting for the preloader to complete and display the actual c ...

Having issues with 'direction' in React withStyles causing errors

I am experiencing an issue with my React website where I am using the withStyles feature to apply styles to a material-ui Grid element. Specifically, when attempting to use direction: "column" in the style, I encounter the error message provided below. Th ...

Developing a Monitoring-Frontend Application with backbone.js

I am in the process of developing a tool for monitoring and analyzing statistics. The current setup is as follows: Collector-Backend: This component receives queries in JSON format from the frontend, fetches and stores them in a cache, and then notifies ...

Set a value after checking with ng-if

I am currently working on creating a table using ng-repeat. Here is the code I have so far: <table class="tab2" > <thead> <tr> <th>Currency: USD '000s</th> ...

Exploring the syntax of Vue's data function

I encountered a syntax error while compiling my assets: Syntax Error: SyntaxError: C:\xampp\htdocs\dtcburger.com\resources\js\components\stripe\STRIPEform3.vue: Unexpected token, expected ";" (51:12) 49 | { ...

Leverage the power of PHP files within your JavaScript code

I have a PHP file with some calculations that I want to integrate into another JavaScript file. How can I pass variables from JavaScript to perform calculations inside the PHP file? Here is my JavaScript code: $("#upload").on("click", function(){ var ...

Initiate node and PM2 application using a batch file

Currently, I have a chat-bot application running on Node.js, which I always keep active using pm2. I am looking to streamline the process of launching the application. Instead of having to run the start command from the console every time, I would like to ...

Converting a boolean value to a boolean type in a CSHTML file

In my cshtml file, I am retrieving the value from the server code. It's a boolean field that returns a boolean value. Order="@Model.OrderModel.IsToday" I attempted to convert it to JSON using @Model.OrderModel.IsToday.ToJson(), but it seems to be tr ...

Firebase (web) deploy encounters an issue due to stripe integration

I recently integrated Stripe into my Firebase function index.js: const stripe = require('stripe')('key'); and created a function for checkout sessions: exports.createCheckoutSession = functions.https.onCall(async(data, context) =&g ...

Utilize Node.js and an API to generate a new problem in GitHub, but encountering an issue where the response

I have been experiencing an issue related to making a Post request to the Github API for creating an issue. I have gone through this post on Stack Overflow but I am seeking assistance in using the request module. Although I have referred to the Github docu ...

The unzipper will disregard any empty directories within the file

I am a Japanese Web Developer. Unfortunately, I struggle with English. https://www.npmjs.com/package/unzipper This library is currently in use by me. Below you will find my code snippet: // unzip module import fs from 'fs-extra' import unzip ...

Implement lazy loading of content on scroll in Grails framework

Currently, I am uploading images and displaying them in a gsp view. My goal now is to implement a functionality where the images load as I scroll down on the page. A friend suggested using jQuery to make an ajax call for this. Can someone please provide g ...

Is it possible to extract data from a table by adjusting Javascript in the inspector tool? The page is only showing today's data, but I'm interested in retrieving historical data by going back

My Desired Action: I am interested in extracting data from the 2nd and 3rd tables on this page. However, the data displayed is specific to the current 'day'. I wish to access readings from September 1st and import them into a Google Sheet. Speci ...

What is the best way to fulfill a promise after a CSV file has finished being read?

I have been utilizing the 'fast-csv' module that can be found at this link (https://www.npmjs.org/package/fast-csv), but I am open to switching to a different one. I attempted promised-csv (https://www.npmjs.org/package/promised-csv) but I had tr ...