将事件发送到范围中的角度指令函数

Send event to angular directive function in scope

本文关键字:指令 函数 范围 事件      更新时间:2023-09-26

我正在尝试创建一个带有angular的指令,用于显示一个通过ajax调用将其选项加载到模板中的多选。这是我现在的指示:

function AngularMultiselect () {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: 'temp.html',
        scope: {
            tipo: "@"
        },
        link: function(scope, element, attrs){
            scope.open_tab = function(){
                element.addClass('open');
                $(document).on("click",function(){ //beign called at the same time
                    console.log("document clicked");
                });
            };
            console.log('multiselect being called');
        }
    }
}

HTML:

<filtro tipo="client"></filtro>

模板内部:

<button type="button"
        class="multiselect btn"
        ng-click="open_tab()">

我遇到的问题是,选项卡在单击的同时打开和关闭。我会使用该事件来停止事件的传播,但我无法发送它…我尝试了open_tab($event),但$event包含'client'。有什么想法吗?

在这里,您可以看到它在工作:http://codepen.io/vandervals/pen/VeZrdV

只需推迟文档点击处理程序附加即可避免此问题:

而不是:

scope.open_tab = function(){
                element.addClass('open');
                $(document).on("click",function(){ //beign called at the same time
                    console.log("document clicked");
                });
            };

只需:

scope.open_tab = function(){
  element.addClass('open');
  $timeout(function() {
    $(document).on("click",function(){ //no longer beign called at the same time
      console.log("document clicked");
    });
  }, 1, false);
};

为了避免触发第二个处理程序的初始点击事件