重新绑定$观察者

时间:2014-11-27 14:58:52

标签: angularjs angularjs-directive angularjs-watch

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();
        }

    };
}]);

点击我的按钮时如何重新绑定$ watcher。?

2 个答案:

答案 0 :(得分:0)

我想,通过调用unregister函数,你想取消绑定侦听器。但是你应该在范围被破坏时这样做,而不是在设置了观察者之后。所以,

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

答案 1 :(得分:0)

要在取消绑定后再次绑定观察者,你需要再次调用$ watch,除此之外没有Angularjs再次绑定的方法。为此,您可以创建一个函数:

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

然后将返回的取消注册函数保存到变量中。

var deWatchProps = watchProps();

再次观看,请致电

var deWatchProps = watchProps();

您还可以创建这样的切换功能:

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