Satish Kumar
Satish Kumar

Reputation: 110

How to apply watcher on a variable without using $scope?

Is there any way to watch changed value of a variable without using $scope?. My manager told me that we may migrate our code to angular2 which do not have $scope so we have to write the code in the way so that when we migrate it to angular2 it needs minimal changes. So now i want to keep track changes of a variable which we do in angular like :

  $scope.$watch('myVar', function() {
    alert('hey, myVar has changed!');
});

Now i want this to something like

app.controller('auditCtrl',
    function($scope, $localStorage) {
        var adc = this;

        angular.extend(this, {
                $state: $state,
                count: 0
            }

            //What i want is something like
            abc.$watch('count', function() {
                alert('hey, count has changed!');
            });
        })

Upvotes: 1

Views: 344

Answers (1)

Founded1898
Founded1898

Reputation: 977

No, thats not possible. But ask yourself, what is the variable you want to $watch for? If it is a form field, you can simply use ng-change.

If you can use es2015 Syntax, you can add Getters and Setters on the Controllers Prototype which then triggers an update Function. Something like this:

let auditCtrl = function () {
  const adc = self;
  adc.counterItem = null;

  // etc.
};

Object.defineProperty(auditCtrl.prototype,
    "counterItem", {
    get: function () {
      return this.counterItem;
    },
    set: function (newValue) {
      this.counterItem = newValue;

      // Call method on update
      this.onCounterItemChange(this.counterItem);
    },
    enumerable: true,
    configurable: true
});

Or, in my opinion the best approach, use a component architecture for your application. With components, you can use some built-in lifecycle-hooks like $onInit, $onChanges etc. This way, you are also thinking in the angular2 way, since you might want to migrate.

Upvotes: 3

Related Questions