Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watching external variable in AngularJS?

I've written a small JS library for Serial communication in a Chrome app, and it works fine on its own. However, we're running into a problem in integration with Angular: I don't have a way to watch a property of the serial object outside the controller from inside, and I have not been able to find a workaround. Ideally, there's a solution that isn't too computationally expensive, bu at this point, I am not ruling out some way to convert the entire library to a more Angular-friendly format. However, in this situation I'm not sure whether it should go in a service or some other format. Any help would be appreciated.

like image 520
Andy Avatar asked Feb 25 '14 01:02

Andy


1 Answers

Just borrowed the idea from here: In AngularJS, how do I add a $watch on the URL hash?

$scope.$watch accepts function as the first argument, so you can do this:

$scope.$watch(function () {
    return mylib.myproperty
}, function (value) {
    // do stuff
});

UPDATE: As noted in the comments, when mylib.myproperty changes the controller won't know about it until the next digest cicle. Since mylib is not angular-enabled you need to use a plain javascript callback mechanism:

mylib.on_myproperty_change(function(){
    $scope.$digest(); // this will cause the $watch to be re-evaluated
});

But since now you already have a mylib.on_myproperty_change you don't really need to $watch anything, so you can delete the watch and just

mylib.on_myproperty_change(function(){
    //do the stuff that you did in the the $watch
    $scope.$digest(); 
});
like image 61
Tony Lâmpada Avatar answered Sep 18 '22 02:09

Tony Lâmpada