2

I'm having some issues using $scope.$watch in an ES6 project. The watch fires once and then never again.

Here's the code:

export class SomeController {
  constructor($log, $scope) {
    'ngInject'
    this.watched = 1;
    $scope.$watch('watched',(nv,ov)=>{
        $log(nv); //only fires once
    });
   }
  otherMethods(){}...
}

Specifically I am using this generator: https://github.com/Swiip/generator-gulp-angular

userqwert
  • 2,193
  • 5
  • 28
  • 50
  • To clarify: Te equivalent ES5 code works just fine? Or what makes you think that this an issue with ES6 specifically? – Felix Kling Apr 06 '16 at 13:48
  • Do you change the value of `watched` somewhere in order to fire the event ? could you provide you html code ? and/or a fiddle ? – Lulylulu Apr 06 '16 at 13:53
  • 1
    I know that the variable is updating as I can do {{someController.variable}} Thanks for the downvotes guys, really constructive. – userqwert Apr 06 '16 at 13:59
  • There is literally no other code to this problem, the watch just doesn't fire. – userqwert Apr 06 '16 at 14:00
  • I beleive it's ES6 as usually $scope.$watch works, however here I'm not binding to the scope firectly, I'm binding everything to the this of the constructor. It could be a ui-router issue I suppose... – userqwert Apr 06 '16 at 14:01

1 Answers1

6

You could try this:

$scope.$watch(() => this.watched, function (nv, ov) {
  console.log(nv);
});

as explained more here.

Here is a fiddle with a demo.

And also, the event fires on $digest cycles on :

  • DOM events (user changing value of an input field, clicking on a button to invoke a JavaScript function and so on)

  • XHR responses firing callbacks

  • Browser's location changes

  • Timers (setTimout, setInterval) firing the callbacks

or if you call it explicitly.

Community
  • 1
  • 1
Lulylulu
  • 1,254
  • 8
  • 17