2

I want to create a new Angular compontent, which should change the status of an object/model and then call the defined callback function.

The code looks like this:

HTML

<status-circle status="obj.status" on-update="save(obj)"></status-circle>

statusCirlcle.js

angular.module('app').component('statusCircle', {
  templateUrl: '/views/components/statusCircle.html',
  bindings: {
    status: '=',
    onUpdate: '&'
  },
  controller: function () {

    this.update = function (status) {
      if(this.status !== status) {
        this.status = status;
        this.onUpdate();
      }
    };

  }
});

The property will be updated correctly (two-way binding works) and the save callback function gets called, BUT the object has the old status property set.

My question: How can I update the object in the callback function?

JSFiddle: https://jsfiddle.net/h26qv49j/2/

Community
  • 1
  • 1
Betty St
  • 2,741
  • 21
  • 33
  • 1
    `this` inside `update` function is different than the outer `this`, refer this [so question](http://stackoverflow.com/q/4886632/2435473), that why you are not updating actual `status` variable, it is different one.. – Pankaj Parkar May 12 '16 at 11:41
  • doesn't change anything when I assign this to a variable before.. the property will be updated correctly with this code but the callback function is called with the 'old' object.. – Betty St May 12 '16 at 11:58
  • 1
    could you please attach plunkr/fiddle? – Pankaj Parkar May 12 '16 at 12:01
  • added a jsfiddle link! – Betty St May 12 '16 at 12:26
  • there seems to be problem related with bindings, it is updating it one digest cycle later.. here is [fiddle](https://jsfiddle.net/uckywyc3/) – Pankaj Parkar May 12 '16 at 12:51
  • thanks! I moved the $timeout to the component - I think it belongs here! https://jsfiddle.net/h26qv49j/4/ - is this really the right approach? – Betty St May 12 '16 at 13:44
  • 1
    no.. it isn't good approach to go... I'd prefer you to pass `obj` object to directive instead of sending just status, so that object reference will get carried to directive & as soon as you change any of the value of it.. – Pankaj Parkar May 12 '16 at 13:50

1 Answers1

0

It looks like in statusCircle.js you should change

this.onUpdate();

to

this.onUpdate({status: status});

and then in the HTML change

<status-circle status="obj.status" on-update="save(obj)"></status-circle>

To

<status-circle status="obj.status" on-update="save(status)"></status-circle>

And lastly... in your controller where your save() function is put

this.save = function(status) {this.obj.status = status};