2015-12-02 58 views
1

我試圖用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

+1

你可以做一個現場演示? –

回答

0

只是推遲文檔點擊處理程序附加以避免此問題:

代替:

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

爲避免初始點擊事件觸發第二個h安德勒

+0

僅適用於第一次 – Vandervals

+0

也是,您還需要在觸發文檔處理程序(您可能不這麼做)後解除綁定文檔處理程序,否則您將多次綁定它。 –