我用兩個指令中的HTML代碼:查詢選擇嵌套AngularJS指令
<div animations>
<h2>Title</h2>
<span class="animateBtn">Animate!</span>
<info-section></info-section>
</div>
首先,是一個屬性指令:
angular.module('app').directive('animations', ['$window', ($window: any) => {
return {
restrict: "A",
link: function ($scope: any, element: any, attrs: any) {
angular.element(document).ready(() => {
let animateBtns = angular.element(element[0].querySelector('.animateBtn'));
if (animateBtns && animateBtns.length) {
for (let i = 0, animateBtnsLength = animateBtns.length; i < animateBtnsLength; i++) {
let currentBtn = animateBtns[i];
currentBtn.addEventListener("click", function() {
.... other code....
});
}
}
..... other code .....
});
}
};
}])
所以,它只是做了querySelector到選擇所有在點擊時必須啓動某個功能的按鈕。 它的工作原理。問題是,第二個指令還包含一個「animateBtn」:
.directive('infoSection', function() {
return {
replace: true,
restrict: 'E',
template: '<div><span class="animateBtn">Animate with this too</span></div>'
}
});
的問題是,在第一個指令(即使我的用戶(文件)。就緒()),選擇回報率只是一個元素(標題下的跨度),它不包含第二個指令的「animateBtn」。
在這裏你可以找到的完整代碼:PLNKR
您不應該嘗試使用querySelector來查找其他DOM元素。如果您想在指令之間建立父子關係,可以通過它們的控制器在它們之間進行通信,並讓子指令將它們綁定到的DOM元素提供給父級。 –
我添加了一個Plunker,你可以在這裏找到:https://plnkr.co/edit/ZzcowjuiYO4dCtlyC22Q?p=preview – panagulis72
正如Oliver已經說過的,你在做什麼是錯誤的。你也不應該把事件處理器放在代碼中 - 這就是jQuery的方式。嘗試閱讀本文,可能會幫助您找出更好的angularjs概念:https://gabrieleromanato.name/introduction-to-angularjs-for-jquery-developers閱讀完之後,請嘗試以AngularJS方式重新創建它,也許可以嘗試使用ng-爲angularjs中的動畫設置動畫:https://docs.angularjs.org/api/ngAnimate – pegla