【问题标题】:Angular directive used twice, override elementAngular 指令使用了两次,覆盖元素
【发布时间】:2015-06-29 08:22:49
【问题描述】:

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

我有 2 个模式:登录模式和注册模式,分别在我的 html 中排序。

模态框位于 modals.html 中,该文件在 html 文件中使用 ng-include 调用,该文件也在 ng-include 中调用,因此我们这里有一个 childscope 的 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 指令,但我打开了第一个。

任何帮助将不胜感激

【问题讨论】:

    标签: javascript jquery html angularjs twitter-bootstrap


    【解决方案1】:

    您确定scope.$parent.$parent.$parent 与您的两个模态不同吗?如果他们有相同的祖父,那么只有最后一个会真正定义 grandOldParent.dismiss 函数是什么。

    老实说,当我看到scope.$parent.$parent.$parent 这个东西时,我有点害怕。始终建议避免使用$parent,因此将其中的 3 个链接起来更加疯狂。

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

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

    这也没用:

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

    应该替换为

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

    (或者如果此事件是异步的并且在 Angular 摘要循环之外,则简单地 scope.$apply)。

    还要注意,scope.$apply 实际上是 $rootScope.$digest,所以 您 $apply 的范围无关紧要。

    更新:您可以在指令 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。

    【讨论】:

    • 我知道使用 $parent.$parent.$parent 很难看。我自己的内在开发者告诉我,这是废话,应该有更简单的东西。我不认为scope.$parent.$parent.$parent 对于这两种模式来说是不同的,因为它们在同一个文件中。我会尽力解决问题并回复你。
    • 对于编辑,Angular 1.3 尚不可用
    • 好的,那我怎么做才能使指令不覆盖第一个模态?感谢您的宝贵时间
    • 我使用的是旧版本的 angular bootstrap 和 angular 1.3(甚至尝试过 1.4.0-beta.6),它就像一个魅力。它使代码方式更清晰,您仅在实际需要时才加载模态模板并使用其自己的控制器。
    • 好吧,我不知道您要通过覆盖此 parent parent parent dimiss 方法来做什么。你不能写scope.dimiss = ...吗?尝试使用scope: true 而不是scope: {}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多