Angular指令使用了两次,覆盖元素

时间:2015-04-21 22:58:07

标签: javascript jquery html angularjs twitter-bootstrap

我试图为模态编写一个简单的指令,以便在我在其中提交表单时将它们关闭。

我有2个模态:Loginmodal和signup模式,分别在我的html中排序。

modals在一个modals.html里面,在一个html文件中用ng-include调用,该文件也在ng-include中调用,所以我们这里有一个 childscope of childscope

我的指示

directive('myModal', function() {
    return {
        restrict: 'A',
        scope : { },
        link: function(scope, element, attr) {
            scope.$parent.$parent.$parent.dismiss = function() {
                console.log(element.hasClass('in')); //returns false
                element.modal('hide');// doesn't work because element is always the second modal
                };
            $(element).bind('shown.bs.modal', function () {
                if (!scope.$$phase && !scope.$root.$$phase)
                    scope.$parent.$parent.$parent.$apply();
                });
            }
        };
});

我不知道为什么link内的元素会被最后一个元素覆盖?

我将my-modal指令应用于我的两个模态,但是我打开了第一个。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

你确定scope.$parent.$parent.$parent与你的两个模态不同吗?如果他们有相同的祖父母,那么只有最后一个将实际定义grandOldParent.dismiss函数。

老实说,当我看到这个scope.$parent.$parent.$parent时,我有点害怕。总是建议避免使用$parent,因此链接其中的3个甚至更疯狂。

你真的需要一个孤立的范围(scope: {}),实际上你操纵它的上层父母吗?为什么不使用继承范围?

可能有一种更清洁的方式来处理这些范围。您是否正在使用,或者您是否使用$modal服务定义了模板和控制器来查看模态的https://angular-ui.github.io/bootstrap/

这也没用:

if (!scope.$$phase && !scope.$root.$$phase)
  scope.$parent.$parent.$parent.$apply();
});

应该替换为

if (!scope.$root.$$phase) {
  scope.$apply();
}

(或简称scope.$apply如果此事件是异步的并且在Angular摘要周期之外)。

另请注意,scope.$apply实际上确实为$rootScope.$digest,因此不会确定您申请的范围。

更新:您可以在指令html中添加ng-click="close",并将其添加到其链接功能中:

scope.close = function() {
  // do stuff on this directive instance
  console.log(element.hasClass('in'));

  // close the modal
  var parent = scope;
  while (!parent.dismiss) { parent = parent.$parent; }
  parent.dismiss();
}

这样,你的指令的每个实例都有自己的close函数(因此不会覆盖任何其他函数),但仍会调用每个实例使用的属于一个模态的唯一dismiss