使用$ compile

时间:2017-05-26 11:07:29

标签: angularjs angularjs-directive angularjs-scope

我需要为小部件实现切换功能。当用户点击最小化按钮时,小部件应该在单击最大化按钮时缩小和展开。

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

});

1 个答案:

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