Connect an Angular Service object to a Controller's Scope and keeping it in sync

I am facing an issue with the interaction between my EmployeeService and EmployeeController. The service contains a specific object which I bind to the controller's scope:

app.controller('EmployeeController', function($scope, EmployeeService) {
    $scope.employee = EmployeeService.getEmployee();
}

Within the HTML template, I display the name of the employee like this:

{{employee.name}}

When I make changes to the employee object in the EmployeeService, such as updating the name, the template reflects the new name. However, if I completely replace the employee object using

EmployeeService.setEmployee({name: 'new name'})
, the template does not update accordingly.

This discrepancy is demonstrated in my Plunk here: http://plnkr.co/edit/k7oKd1VgsBvMGvVdP5kM?p=preview

In the provided Plunk, the functionality works for Employee Controller/Service but not for Manager Controller/Service. Any insights or help on this matter would be greatly appreciated.

Answer №1

Ensure the controller is able to monitor any changes in the manager.

$scope.$watch(function() {
    return ManagerService.getManager();//<--when this changes
  }, function(newManager) { //<-- execute this function
    $scope.manager = ManagerService.getManager();
  });

Check out this updated Plunkr for one method of accomplishing this: http://plnkr.co/edit/YE72JcxDSFqfZLH32ERy?p=preview

Answer №2

The reason for this behavior lies in how angular keeps track of the original object. When you use {{employee.name}}, angular monitors changes to the reference of the object. As noted by you: modifications to

EmployeeService.getEmployee().name
are detected and displayed in the view.

However, when you call

EmployeeService.setEmployee({name: 'new name'})
, angular replaces the observed object with a new one while still keeping an eye on the old one. This results in your alteration going unnoticed by angular, leading to no update in the view.

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

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

Tips for excluding the HTTP OPTIONS request from being intercepted by the express.js authentication middleware

I have set up a backend API using express.js that interacts with an AngularJS single-page application. To secure access to specific resources, I am utilizing token authentication to verify clients. In order to validate whether the incoming request from th ...

Error encountered upon initializing Node-RED due to the presence of an unexpected token while incorporating the NPM module "file-exists" into the

Currently, I'm in the process of developing an application using Node-RED and I'm looking to incorporate some NPM modules into my project. One particular module from James Thom caught my attention, called node-red-contrib-npm, which automates the ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

The container layout in the Angular Material design page is not displaying correctly

After developing a basic page in AMD on my local machine, I decided to use <div layout="row"> to split the content into two columns similar to the bootstrap col-md-6 setup. I found this useful link: [https://material.angularjs.org/1.0.5/layout/contai ...

What is the best way to incorporate dynamic data from Firestore into a function using the `where()` method, while also utilizing the `snap.size` property to accurately count the total number of queries

I am facing an issue while trying to fetch data dynamically from firestore using a where() function. The specific error message I encountered is: TypeError: vaccines is not a function The user collection: [![enter image description here][1]][1] Here a ...

How can you make the browser window scroll horizontally when a div is clicked using jQuery?

I have an image of an arrow inside a div. The div is positioned fixed in the bottom right corner of an extremely wide page. Is there a way to utilize jQuery to scroll the window 600px to the right each time the arrow is clicked? Also, can I detect when th ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Display the accurate duration based on the dates selected in an HTML form automatically

If someone has office hours on Monday, Wednesday, and Friday from 7:00 am to 7:00 pm, and on Tuesday and Thursday from 10:00 am to 9:00 pm, the dropdown menu should display only the timings of 7:00 AM to 7:00 PM if the selected date is a Monday, Wednesda ...

Having trouble with submitting the second stage of a multi-step form through Ajax technology

I'm currently tackling a multi-step form project using JavaScript, specifically focusing on submitting the second step of the form via Ajax. I've taken the initiative to create a distinct JavaScript file titled ajaxRequest.js to manage the Ajax r ...

Is Apache required for running NodeJs?

Recently, I set up a web project on my local machine following a tutorial. With the help of XAMPP, I was able to install MySQL and Apache to run my Node.JS backend. Now, I'm looking into hosting the project on an external server to make it accessible ...

Disallowing selection on input text field

I am seeking to disable selection on an input field while still allowing for focusing, with the following criteria: Preventing selection via mouse Preventing selection via keyboard (including Ctrl+A, shift+arrows) Permitting focus on the field using both ...

Challenge encountered while creating a child tag that can be assigned to multiple parent tags

I have an xml format like the one provided. <xml> <parent id="0"> <child type="name"> </child> <child type="age"> </child> </parent> <parent id="1"> <ch ...

Reveal each element individually upon clicking the button

I am trying to display 5 div elements one by one when clicking a button, but the current code is not working. I am open to alternative solutions for achieving this. Additionally, I want to change the display property from none to flex in my div element. ...

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

Iterate over JSON elements beginning with a specific pattern

What is the best way to iterate through JSON objects that specifically start with a certain format? For example, if we have a JSON structure like this: { "END": true, "Lines": "End Reached", "term0": { "PrincipalTranslations": { // nest ...

Error in Angular: Http Provider Not Found

NPM Version: 8.1.4 Encountered Issue: Error: Uncaught (in promise): Error: Error in ./SignupComponent class SignupComponent_Host - inline template:0:0 caused by: No provider for Http! Error: No provider for Http! The error message usually indicates the a ...

Combining multiple conditions with Sequelize in a JOIN statement

Currently, I am attempting to execute a query using Sequelize ORM with a custom join condition. For example: User.findAll({include: [{model: Post, where: {active: true}}] Here is the result of the join condition: INNER JOIN `posts` AS `post` ON `users`.` ...