我認爲應該通過將兩個標頭包裝在一個指令中,例如headers
來做到這一點。然後在第二個標題的指令查詢中,如果存在,則將ui-scrollfix
指令應用於它。
HTML
<div ng-app='app' ng-controller="aController">
<div headers>
<div id="main-header"> main header </div>
<div id="second-header" ui-scrollfix> second header </div>
</div>
</div>
JS
var app = angular.module('app', []);
app.controller('aController', ['$scope', function (scope) {
}]).directive('uiScrollfix', [function() { // this is just to check that the directive is applied to the element
return {
restrict: 'A',
link: function (scope, el, attrs) {
el.on('click', function() {
console.log(el[0].textContent);
});
}
}
}]).directive('headers', ['$compile', function ($compile) {
return {
restrict: 'A',
link: function (scope, el) {
var directiveEl = el[0],
mainHeaderEl = directiveEl.querySelector('#main-header'),
secondHeaderEl = directiveEl.querySelector('#second-header'),
$mainHeaderEl = angular.element(mainHeaderEl);
if (secondHeaderEl) {
$mainHeaderEl.attr('ui-scrollfix', '');
$compile($mainHeaderEl)(scope);
}
}
}
}]);
JSFIDDLE