Rebind the $watcher

434 views Asked by At

HTML:

<br/><button class="btn btn-primary" ng-disabled="enableCompare()" ng-click="on_compare_plateformes($item)">Comparer</button>

JS:

propertiesModule.controller('PropertiesComparePlateformesCtrl', ['$scope', 'compareService', '$routeParams', 'PropertiesService', 'ApplicationService', 'PlatformService', 'Page', function ($scope, compareService, $routeParams, PropertiesService, ApplicationService, PlatformService, Page) {

     $scope.on_compare_plateformes = function () {
    ...
    };
..
}]);

propertiesModule.directive('propertiesListCompare', ['compareService', function (compareService) {
    return {
        restrict: 'E',
        scope: {
            properties: '=',
            propertiescible: '=',
            application: '=',
            applicationcible: '=',
            undo: '=',
            myselectref: '=',
            myselectcible: '='
        },
        templateUrl: "properties/properties-list-compare.html",
        link: function (scope, element, attrs) {
            // scope.$watch("propertiescible", function () {
            var unregister = scope.$watch('[properties, propertiescible]',function () {
                  ...
              }, true);
                 ...
           unregister();
        }

    };
}]);

How to rebind the $watcher when i click my button .?

2

There are 2 answers

0
Ivan Demchenko On

I guess, by calling unregister function you want to unbind listener. But you should do it when the scope is being destroyed, not right after watcher has been set. So,

link: function (scope, element, attrs) {
  var unregister = scope.$watch('[properties, propertiescible]', function () {
  // do stuff
  }, true);
  scope.$on('$destroy', unregister);
}
0
ahmadalibaloch On

To bind the watcher again after unbinding you need to call the $watch again, there is not Angularjs way to bind again other than this. To do this you can create a function:

function watchProps(){
    return scope.$watch('[properties, propertiescible]', function () {
              ..
           }, true);
    }

and then save returned de-registeration function into a variable.

var deWatchProps = watchProps();

To watch again just call

var deWatchProps = watchProps();

You can also create a toggle function like this:

function toggleWatchProps(){
        if(scope.watchProps)
        {
            scope.watchProps();
        }
       else{
           scope.watchProps = scope.$watch('[properties, propertiescible]', function () {
              ..
           }, true);
        }
    }