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

What is the best way to retrieve ul li values using AngularJS?

I am looking to extract the content of li elements within a ul element in an AngularJS controller and save them into an array. Sample HTML Code: <ul id="list" my-directive> <li>A</li> <li>B</li> <li>C ...

Using state in a ReactJS and Rails Ajax request

I am currently working on a ProductItem component that triggers an AJAX post call to create a basket item when the user clicks 'Add to Basket'. Despite setting state correctly in the Product Item component, I am facing an issue where I am unable ...

Issue with Material UI dropdown not selecting value on Enter key press

I have encountered an issue with the material UI dropdown component that I am using. When I navigate through the dropdown options using arrow keys and press enter, the selected value does not get highlighted. Below is the code snippet for the dropdown: ...

Utilizing Express middleware to serve routes in Sails.js

I am currently working on a sails app where the routes and static assets are served from the root location, which is functioning properly. However, I am looking to integrate an express middleware to serve these routes and assets from a specific path. To s ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

Updating MongoDB collections in Mongoose with varying numbers of fields: A step-by-step guide

Updating a mongodb collection can be challenging when you don't know which fields will be updated. For instance, if a user updates different pieces of information on various pages, the fields being updated may vary each time. Here is my current appro ...

How can we capture the current row's value for later retrieval?

Using datatables to display data from a mySQL database, I am looking to extract the current row's value and present it in a modal for editing. This is how the data is integrated into Datatable: $(document).ready(function() { $(' ...

What causes the auto focus directive to fail to function properly?

I'm having trouble getting the auto focus directive to work. Can anyone take a look at my code? It seems like there might be an issue with it. var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', functio ...

Issues with Ionic Deploy causing app to not update

I am currently working on implementing ionic deploy in my app, but I have encountered some errors. The specific errors I am facing are as follows - Failed to load resource: the server responded with a status of 422 (UNPROCESSABLE ENTITY) ionic.cloud.min. ...

The loop within a loop is causing excessive lag and is on the verge of crashing the

I need help with optimizing the performance of my app that retrieves json data. The json file contains nearly one thousand words structured like this: {"THEMES":{"THEME1":["ITEM1","ITEM2","ITEM3"],"THEME2":["ITEM1",...]...}} The size of the file is aroun ...

What is the best way to pause the function execution until the ajax call is finished?

I have the following code snippet: function validate(){ if (document.getElementById('<%=txtSeqNo.ClientId %>').value.trim() == "") { alert('Please enter Sequence number.'); return false; } var result = checkduplicateseq( ...

Adjust the cursor in a contenteditable division on Chrome or Webkit

Is there a way to set the caret position in a contenteditable div layer? After trying different methods and doing some research online, I finally found a solution that works in firefox: function set(element,position){ element.focus(); var range= w ...

Transforming Ember's ajax query string

Using ember-model, I am making a request like this: App.Video.find({'sort':'createdAt+asc'}); to retrieve a sorted list of videos. This should result in the following request: http://localhost:1337/api/v1/videos?sort=createdAt+asc How ...

Invalid Resize Argument Causes Background to Not Appear on IE Browser

I have encountered a problem where the background (BG) image is not appearing in Internet Explorer (IE). I am struggling to find a solution for this issue. BG Problem Below is the code snippet showing how I implemented the background image. I have used a ...

Tips for synchronizing text field and formula field content on MathQuill 0.10

I am currently working on creating a WYSIWYGish input element for my formula, along with a LaTeX input element. <span id="editable-math" class="mathquill-editable"></span> The goal is to make these two elements work synchronously. Here's ...

Transitioning from Gulp 3 to Gulp 4: encountering issues with starting the http server using gulp serve

Within my AngularJS 1.7 project, I successfully upgraded my gulp configuration files from version 3.9 to 4.0.2. However, encountering an issue where the http server fails to start when running the command "gulp serve" I have made the following changes: C ...

send back the result to the primary function

I need help with this code. I'm trying to return the budget from callbacks in the main function. How can I return a value from the main function? // This method returns the current budget of the user getCurrentBudget: function (req) { var reqTok ...

Is there a way to specify object keys in alignment with a specific pattern that allows for a variety of different combinations

I am seeking a way to restrict an object to only contain keys that adhere to a specific pattern. The pattern I require is: "{integer}a+{integer}c". An example of how it would be structured is as follows: { "2a+1c": { // ... } } Is there a ...

What exactly comprises an HTTP Parameter Pollution attack within the context of Node.js and Express.js?

I came across this information on https://www.npmjs.com/package/hpp According to the source, "Express populates http request parameters with the same name in an array. An attacker can manipulate request parameters to exploit this vulnerability." I am cur ...

Unexpected behavior observed when implementing form-based authentication with AngularJS on Websphere platform

Currently, I am tackling a project in AngularJS that involves form-based authentication. However, I am facing some unexpected behavior that is proving to be quite elusive to track down. The application is hosted on Websphere 8.0.0.10, and session manageme ...