我认为应该通过将两个标题包装在一个指令中来做到这一点 say 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