1

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 selected 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 name property, rather than assign a new object, I got no joy.

Community
  • 1
  • 1
leota
  • 1,636
  • 2
  • 13
  • 33

1 Answers1

1

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

main.service.js

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.

box.component.js

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
        }
    }
});

parms-bar.component.js

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">
    <a>
        {{$ctrl.selected.name}}
    </a>
</div>
Lex
  • 6,758
  • 2
  • 27
  • 42
  • Glad it worked. I just realized that the sample I provided had a line of code that isn't necessary. In the box component you don't need `mainService.selected = box` because `box` is already a reference object. My bad. – Lex Jul 09 '16 at 16:45