Modify a variable within the service using multiple controllers

Seeking a more efficient way to accomplish the following:

This is my service:

dashboardApp.service('MessagesService', function () {
   var message = "";

    this.update = function (new_message) {
        message = new_message;
    };

    this.get = function () {
        return message;
    }
});

Now, let's consider this controller:

dashboardApp.controller('GroupPageController', function($scope, MessagesController){
    $scope.message = MessagesController.get();
})

The $scope.message variable is used in my HTML page like this:

<h3 ng-bind="message"></h3>

Additionally, there is a second controller:

dashboardApp.controller('ChangeController', function($scope, MessagesController, $http){

    $scope.sendEmail = function () {

        $http({
            method: "post",
            url: "/enterprises/vouchers/_send",
            data: {
                group_id: group_id,
                group_student_ids: group_student_ids
            }
        }).success(function (response) {
            MessagesService.update(response.message);
        }).error(function () {
            console.log("failed")
        });

    }

})

When a button is clicked in the above controller, it fetches data from a web API and updates the variable within the service. The expectation is for the $scope.message variable in the first controller to update as well, reflecting the change on the HTML page. However, this does not occur as desired. As a solution, I am currently using $watch:

$scope.$watch(function () {
    return MessagesService.get();
}, function (newValue, oldValue) {
    if (newValue !== oldValue) {
        $scope.message = MessagesService.get();
    }
});

Though the current setup works effectively, some sources discourage the use of $watch within controllers.

Is there an alternative approach to achieve this functionality without relying on $watch?

Answer №1

Sharing data between controllers can be done without using a watcher. All you have to do is declare the service on the scope and then update the properties of the service with your scope.

For example, you can check out this sample code: http://plnkr.co/edit/zNGnkfEsCIvLssCyHivg?p=preview

var app = angular.module("myApp", []);
    
app.controller('myCtrl', ['$scope', 'sharedDataService', function($scope, sharedDataService){

  $scope.sharedDataService = sharedDataService;
  
}]); 

app.controller('mySecondCtrl', ['$scope', 'sharedDataService', function($scope, sharedDataService){

  $scope.sharedDataService = sharedDataService;
  
}]); 

app.service('sharedDataService', [function(){
  return {
    someData: "Share Me"
  }
}]);
<!DOCTYPE html>
<html>

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33525d54465f52411d18f52514f4e4b554c02514f52">[email protected]</a>" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
    <link href="style.css" rel="stylesheet" />
    <script src="script.js"></script>
  </head>

  <body ng-app="myApp">
  
    <div ng-controller="myCtrl"> 
      Controller one:
      
      <input ng-model="sharedDataService.someData">
      
    </div>  
        
    <br>
    
    <div ng-controller="mySecondCtrl"> 
      Controller two:
      <input ng-model="sharedDataService.someData">
      
    </div>  
    
  </body>

</html>

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

Utilizing ng-change in an AngularJS directive with isolated scope to transition towards a component-based architecture. Let's evolve our approach

I've been struggling to get ng-change to trigger in my directive with an isolated scope. I'm working on transitioning from ng-controller to a more component-based architecture, but it's turning out to be more difficult than I anticipated. I ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...

Encountering a Typescript error when trying to invoke a redux action

I have created a redux action to show an alert message export const showAlertConfirm = (msg) => (dispatch) => { dispatch({ type: SHOW_ALERT_CONFIRM, payload: { title: msg.title, body: msg.body, ...

Ways to extract a value from an HTML form in ASP.NET when using Html.EnumDropDownListFor

I am a beginner in ASP.NET and I recently set up a form that allows input from a C# enum: <form method="get"> <div class="form-group"> <label>Select Type:</label> @Html.EnumDropDownListFor(x = ...

Encountering a problem when looping through a JSON response

After making an Ajax call, I received the JSON response below. studentList: { "currentStudent":0, "totalStudent":11, "studentDetails": [{ "adId":1, "adName":"BMB X5", "sfImage":{ "imageName":"Desert", "image ...

Having trouble changing the title with Switch/Case in Angular?

I am facing an issue where the title is not displayed as expected based on the environment value in appConfig.json. appConfig.json "env": "stage", app.component.ts env: string; constructor( private configService: ConfigService ) ...

Form featuring two buttons with distinct values for submitting

<form action="here.php" method="POST"> <input type="text" name="text"> <div id="one"> <input type="hidden" name="aaa" value="one"> <input type="submit" value="Send"> </div> <div id="two"> <input type= ...

Substitute all instances of numbers in scientific notation with standard numbers

I need help handling a large XML string containing decimal values in both regular and scientific notation. I am looking for a way to convert all exponential values to regular notation directly. So far, I have developed the following Regex pattern that ide ...

Exploring the integration of Glide js within a Next js environment

I am trying to figure out how to use a script tag in the next JavaScript _app.js component for utilizing the Glide JavaScript carousel. However, I am facing difficulties in using the script tag. Can someone help me out by providing guidance on how to inc ...

Whenever I try to execute the ajax request for signing up or logging in, it fails to work as expected

While working on a project that follows the MVC pattern, I encountered an issue with sign up and login forms. To break down the process, it involves three parts: 1- frontend (HTML, CSS, JavaScript), 2 - server-side (PHP), and 3 - database (MySQL). The prob ...

The issue of TypeError arising while invoking a method within TypeScript Class Inheritance

Currently, I am developing a Node.js application with TypeScript. In this project, I have a base controller class named BaseController and a derived controller called SettingController. The intention is for the SettingController to utilize methods from the ...

Is there a maximum number of iterations allowed when looping through arrays in Jade/Express?

I'm currently facing an issue while trying to navigate through a nested array structure in my Jade code. It seems like I've reached a limitation. div().slidePreview ul each slide in slides div each section in slide ...

Encountering an issue when attempting to import a non-source module from a node library while running a Typescript script

I have a script that takes input and utilizes the three.js library to apply geometric transformations to the data. I execute this script using ts-node pipeline.ts. Here is the structure of my project: ├── package-lock.json ├── package.json ├ ...

Is it possible to utilize THREE js ExtrudeGeometry to manipulate a shape along a jagged path?

Is it possible to use CatmullRomCurve3 to extrude over a sharp line, as shown in the image below: https://i.sstatic.net/wJNEv.png I am looking to achieve the following result: https://i.sstatic.net/Fe87K.png The goal is to achieve this with minimal pol ...

Could anyone clarify the concept of how a function is able to be equivalent to zero?

function checkForSpecialCharacters(text) { var specialChars = [";", "!", ".", "?", ",", "-"]; for(var i = 0; i < specialChars.length; i++) { if(text.indexOf(specialChars[i]) !== -1) { return true; } } ...

Obtain the complete file path using JavaScript

Imagine you have a web application utilizing NodeJS and ReactJS, both working on your local machine. In this setup, NodeJS is capable of accepting files selected from the ReactJS GUI via a simple file upload feature, like so: <input type="file" id="fil ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

What steps are involved in setting up a dropdown side navbar?

Is there a way to automatically activate the next dropdown in the side navbar when I click on the 'Next' button? And similarly, can we open the previous dropdown in the side navbar when clicking the 'Previous' button? ...

How to display an object in JS format using React?

Currently, I am tackling a project that presents me with the following situation: myjson: { completeName: "my name is {this.state.myName+ " "+this.state.surname}" } component.js var Component = React.createClass({ getInitialState: function() { ...

How can I keep a Fixed Positioned Background from Moving to the Top of the Page when Clicked?

I've created a unique image/lightbox viewer for displaying multiple images on a single page. However, there seems to be an issue with the .no-scroll class jumping to the top of the page every time it is triggered by a .click() event. I suspect this mi ...