0

I have an EmployeeService that I inject into an EmployeeController. The EmployeeService contains an object.

I bind Service object into Controller Scope:

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

HTML template displays the name of the Employee:

{{employee.name}}

If I manipulate the employee object in the EmployeeService ... i.e. EmployeeService.getEmployee().name = 'new name', the template displays the new name.

However, if I replace the employee object in the EmployeeService ... i.e. EmployeeService.setEmployee({name: 'new name'}) the template does not display the new name.

Why is replacing the Service object not reflected in the template?

I have the following Plunk that demonstrates this: http://plnkr.co/edit/k7oKd1VgsBvMGvVdP5kM?p=preview

In my Plunk, Employee Controller/Service works and Manager Controller/Service does not.

If anyone could help me understand what is going on I would really appreciate it.

1

2 Answers 2

1

You need the controller to watch for changes to the manager.

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

Here is an updated Plunkr with one way to do it: http://plnkr.co/edit/YE72JcxDSFqfZLH32ERy?p=preview

Sign up to request clarification or add additional context in comments.

Comments

1

This is because of the way angular watches the original object. If you declare {{employee.name}} angular starts watching the object reference for changes. As you said: changes to EmployeeService.getEmployee().name are correctly noticed and reflected in the view.

But EmployeeService.setEmployee({name: 'new name'}) replaces the watched object with a new object while angular still watches the original one. Hence your change is not recognized by angular and the view does not update.

2 Comments

Okay ... that makes sense. The unfortunate problem I have is that this is a simple example I put together and our enterprise app ... Restangular pulls down a big complex object, and I need to put it into a Service and bind it to Controller Scope. Any ideas?
Only add this object to the scope once it is retrieved. $scope.employee = ... or copy the properties to the watched object. And please accept this answer if it solved your original question to help others...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.