Samantha J Samantha J - 1 year ago 131
AngularJS Question

How can I monitor the value of some scope variables for changes?

I have this code in my appController. The code sets the value of $scope.cursorWait to true when there's an HTTP in progress:

$scope.$on('cfpLoadingBar:started', function (event, data) {
$scope.cursorWait = true;

$scope.$on('cfpLoadingBar:completed', function (event, data) {
$scope.cursorWait = false;

I also have this in my connect service. The functions get called when the internet is disconnected:

isConnectedHandler = (): void => {
var self = this;
self.$rootScope.connected = true;
self.$rootScope.disconnected = false;
self.connectMessage = null;
self.minutes = 0;

isNotConnectedHandler = (): void => {
var retry = 0;
var self = this;
self.$rootScope.connected = false;
self.$rootScope.disconnected = true;

How could I monitor the value of $rootScope.disconnected and cursorWait to then set the value of a rootScope variable waiting to true if either $rootScope.disconnected or cursorWait were true?

Answer Source

Assuming your controller has several ViewModels it would like to monitor, let's say cursorWait and connected for example. In this case, Angular provide you with the watchGroup ability. This way you can monitor several variables and in the case one of them change, you may react accordingaly.

Sample Code (Using Typescript for demonstration)

$scope.$watchGroup([()=> { return this.cursorWait }, ()=> { return this.connected}], 
(oldValues, newValues)=> {

      /* The callback gets an array of `oldValues` and an array of `newValues`, 
         the index according to the variables you were watching */

For more information, refer to Angular documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download