2017-05-26 76 views
0

我需要为小部件实现切换功能。当用户点击最小化按钮时,窗口小部件应分别收缩和展开,当分别点击最大化按钮。

Widget

widget

我试图实现与下面的代码此功能。 按预期工作的功能,但它正在多次注册事件(我发出事件并捕获filterTemplate指令)。

我们该如何多次停止注册事件?

是否有无论如何编译一次,并在切换按钮绑定模板/指令到DOM,并使其工作的其余功能。

所以你能帮我解决这个问题。

function bindFilterTemplate(minimize) { 
    if ($scope.item && !minimize) { 
     if ($scope.item.filterTemplate) { // filter template is custom 
              // directive like this 
              // "<widget></widget>" 
      $timeout(function() { 
       var filterElement = angular.element($scope.item.filterTemplate); 
       var filterBody = element.find('.cls-filter-body'); 
       filterElement.appendTo(filterBody); 
       $compile(filterElement)($scope); // Compiling with 
        // current scope on every time when user click on 
        // the minimization button. 
      }); 
     } 
    } else { 
     $timeout(function() { 
      element.find('.cls-filter-body').empty(); 
     }); 
    } 
} 
bindFilterTemplate(); 
// Directive 
app.directive('widget', function() { 
    return { 
     restrict: 'E', 
     controller: 'widgetController', 
     link: function ($scope, elem) { 
      // Some code 
     } 
    }; 
}); 


// Controller 
app.controller('widgetController', function ($scope) { 

    // This event emitting from parent directive 
    // On every compile, the event is registering with scope. 
    // So it is triggering multiple times. 
    $scope.$on('evt.filer', function ($evt) { 
     // Server call 
    }); 

}); 
+0

你能告诉我们你的指令代码在哪里你绑定事件,以及如何? –

+0

@Pankaj Parkar更新的代码。 –

+0

请您检查 –

回答

0

我用$scope.$new()创造新的范围修复了这个问题。

当用户最小化销毁范围的小部件时。

请让我知道如果你有任何其他的解决方案来解决这个问题。

function bindFilterTemplate(minimize) { 
     // Creating the new scope. 
     $scope.newChildScope = $scope.$new(); 
     if ($scope.item && !minimize) { 
      if ($scope.item.filterTemplate) { 
      $timeout(function() { 
       var filterElement = angular.element($scope.item.filterTemplate); 
       var filterBody = element.find('.cls-filter-body'); 
       filterElement.appendTo(filterBody); 
       $compile(filterElement)($scope.newChildScope); 
      }); 
      } 
     } else { 
      $timeout(function() { 
      if ($scope.newChildScope) { 
       // Destroying the new scope 
       $scope.newChildScope.$destroy(); 
      } 
      element.find('.cls-filter-body').empty(); 
      }); 
     } 
     }