在移动元素时防止Angular JS指令被激活两次

时间:2014-09-05 18:27:41

标签: angularjs angularjs-directive angularjs-scope

每次附加元素时,它都会再次触发指令。我只想将 elem 移到 icr-main-modal-placement 元素中。

.directive('icrMainModal', function() {
  return {
    restrict: 'E',
    templateUrl: 'views/icr-main-modal.html',
    scope: {
      state: '=icrVState'
    },
    transclude: true,
    compile: function(elem, attrs) {

      angular.element('icr-main-modal-placement').append(elem); // because of this, the directive is fired again. I just want to move elem into 'icr-main-modal-placement'

      return function(scope, elem) {

        scope.$on('$destroy', function() {
          return elem.remove();
        });

      };

    }
  };
});

1 个答案:

答案 0 :(得分:1)

我能想到的一种方法是为Attribute而不是Element制作这个指令并删除编译/链接方法中的属性吗?

.directive('icrMainModal', function() {
  return {
    restrict: 'A',
    templateUrl: 'views/icr-main-modal.html',
    scope: {
      state: '=icrMainModal'
    },
    transclude: true,
    compile: function(elem, attrs) {
      elem.removeAttr('icr-main-modal');
      angular.element('icr-main-modal-placement').append(elem); 

      return function(scope, elem) {

        scope.$on('$destroy', function() {
          return elem.remove();
        });

      };
    }
  };
});