0

我正在使用angular1的組件設計來構建此應用程序。當用戶點擊按鈕時,我做了一個指令,在按鈕上產生連鎖反應。這是一種常見的行爲,所以我在指令中採用了它。 現在我想添加另一個事件監聽器到組件控制器$ postLink()鉤子中的同一個按鈕,這會導致指令事件監聽器在執行中失敗。

如何解決這個問題。我想要聽兩個事件。

下面是我的漣漪效應指令。我正在使用commonjs加載模塊,所以不要被這些打擾。

var app=require('../../../../Development/Assets/Js/appConfig'); 
app.directive('wave',waveConig); 
waveConig.$inject=['$compile','$timeout']; 
function waveConig($compile,$timeout){ 
return{ 
    restrict:'A', 
    link:waveLink 
}; 
function waveLink(scope,elem,attr){ 
    var waveColor = attr.color; 
    elem.unbind('mousedown').bind('mousedown', function (ev) { 
     var el = elem[0].getBoundingClientRect(); 
     var top = el.top; 
     var left = el.left; 
     var mX = ev.clientX - left; 
     var mY = ev.clientY - top; 
     var height = elem[0].clientHeight; 
     var rippler = angular.element('<div/>').addClass('wave'); 
     rippler.css({ 
      top: mY + 'px', 
      left: mX + 'px', 
      height: (height/2) + 'px', 
      width: (height/2) + 'px', 
     }); 
     if (waveColor !== undefined || waveColor !== "") { 
      rippler.css('background-color', waveColor); 
     } 
     angular.element(elem).append(rippler); 
     $compile(elem.contents())(scope); 

     $timeout(function() { 
      angular.element(rippler).remove(); 
     }, 500); 

    }); 
} 
} 

下面是我的組件控制器代碼。

verifyCtr.$inject=['$element','verifyService','$scope']; 
function verifyCtr($element,verifyService,$scope){ 
    console.log('verify component is up and working'); 
var $this=this; 

var serviceObj={ 
    baseUrlType:'recommender', 
    url:'https://httpbin.org/ip', 
    method:1, 
    data:{} 
}; 

$this.$onInit=function(){ 
    verifyService.getData(serviceObj,{ 
     success:function(status,message,data){ 
      $this.data=data; 
     }, 
     error:function(status,message){ 
      alert(status,'\n',message); 
     } 
    }); 
}; 
$this.$onChanges=function(changes){}; 
$this.$postLink=function(){ 
    angular.element(document.querySelector('.addNewTag')).bind('click',function(){ 
console.log('hi there you clicked this btn'); 
}); 
}; 
$this.$onDestroy=function(){ 
    angular.element(document.querySelector('.addNewTag')).unbind('click'); 
    var removeListener=$scope.$on('someEvent',function(ev){}); 
    removeListener(); 
}; 
}module.exports=verifyCtr; 

當我運行它。組件單擊事件偵聽器被觸發。但該指令無法執行。我不知道是什麼原因導致這個問題,我希望他們都能工作。

回答

0

花了一段時間才弄明白。

document.querySelector('.class-name') ; 

返回一個html元素數組。和

angular.element(elem).bind() 

適用於單個角度元素。所以我不得不用一種獨特的方式來識別元素我,通過Id。所以我做了什麼是

angular.element(document.querySelector('#id')).bind(); 

還有其他的方法來做類名也。我們可以在數組上創建並獲取我們的元素並將事件綁定到它。