0

This is my current implmentation to fire callback on customVar get change using $watch...

module.directive('mudirective', function() {
    return {
        scope: {
            callback: '&'
        },
        template: '<h1>Hello</h1><button ng-click="changeVaar()>Click</button>"',
        controller: function($scope) {
            $scope.customVar = false;
            $scope.changeVaar = function() {
               // some large logical execution
               // which set customeVar
               $scope.customVar = '';//some value assgined
            };
        },
        link: function($scope) {
            $scope.$watch('customVar', function() {
                $scope.callback();
            });
        }
    };
});

But i would like to replace this $watch with setter...

Can anybody has idea how could it be possible?

OR

Other option to avoid $watch function but fire callback on customVar changes.

But callback should be fire once it is confirmed that customVar has changed in directive itself.

2
  • How is your customVar changed? If it is in an input you can just do <input ng-model="customVar" ng-change="callback()" Commented Jan 18, 2017 at 10:36
  • 1
    Why dont you call the $scope.callback() towards the end of $scope.changeVaar = function() { function after setting the value to $scope.customVar Commented Jan 18, 2017 at 11:08

1 Answer 1

0

First, I will answer the comments under the question. I had this use case when I saw a controller putting a watcher on a scope value only to detect changes while the value was changed only by assignments inside the controller itself...

The watch was calling a function updating the UI depending on the assigned value (null or not, whatever).

Of course, we could call this function on each assignment. Or replace the watch with a function setting the value given as parameter, and calling this function. But somehow, using a setter was more "transparent", made a minimal set of changes, and you are sure not to miss an assignment.

On hindsight, it is similar to the way MobX works (go see this library if you have complex dependency watching to do).

Second, here is how to do it:

Object.defineProperty($scope, 'watchedValue',
{
    set(newValue) { $scope._watchedValue = newValue; this.doSomethingWith(newValue); },
    get() { return $scope._watchedValue; },
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.