【问题标题】:Rebind the $watcher重新绑定 $watcher
【发布时间】:2015-01-26 05:19:03
【问题描述】:

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 .?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-watch


    【解决方案1】:

    我猜,通过调用unregister 函数,你想解除监听器的绑定。但是你应该在作用域被销毁时这样做,而不是在观察者被设置之后。所以,

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

    【讨论】:

      【解决方案2】:

      解除绑定后要再次绑定watcher,需要再次调用$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);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-14
        • 2011-03-14
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 2012-12-11
        相关资源
        最近更新 更多