leota leota - 7 months ago 25
Javascript Question

Scope value not updating when service variable changes

I've a component (parms-bar.component.js) which is supposed to update when I click on the button (box.component.js), but it's not happening. I'm trying to let them communicate using the "selected" variable in the service (main.service.js).
When you launch the app "test node" is displayed by my "parms-bar" component. On the button click it should change to "Box", but it's not.

Here you can see a live example

I've also read the answer to this question which says that I'm probably replacing the memory location that my

is associated to every time I assign it a new value while the scope is stuck pointing to the old location.
But even trying to modify only its
property, rather than assign a new object, I got no joy.

Lex Lex

You're having object reference issues. The easiest way to fix this is to change your service to return a setter and getter.


angular.module('app').service('mainService', function(){
    var selected = {name: "test node"};

    var service = {
        get selected(){
            return selected;
        set selected(value){
            selected = value;
    return service;

Now you can change your other modules to get and set this object directly.


angular.module('box').component('box', {
    templateUrl: 'box.template.html',
    controller: function boxController(mainService){
        this.addBox = function () {
            var box = mainService.selected;
            //Set custom properties
            box.name = "Box";
            //Set as selected
            //mainService.selected = box; <-- This is not needed


angular.module('parms-bar').component('parmsbar', {
    templateUrl: 'parms-bar.template.html',
    controller: function parmsController(mainService){
        this.selected = mainService.selected;

And then use the object in your parms-bar.template.html

<div id="parms-bar">