Mitya Ustinov
Mitya Ustinov

Reputation: 903

Apply AngularJS directive (ui-scrollfix) conditionally

I'm using ui-scrollfix directive from UI.Utils to make so called sticky header. It works fine. There are two headers in the app. Main one is constantly on the page and second one appears only in certain pages.

<div id="main-header" ui-scrollfix></div>

<div id="second-header" ui-scrollfix></div>

What I need to do is that ui-scrollfix directive was added or applied to main-header, if second-header is present.

Is that possible to achieve?

Thank you!

Upvotes: 0

Views: 243

Answers (1)

dcodesmith
dcodesmith

Reputation: 9614

I think should do this by wrapping both headers in a directive say headers. And then in the said directive query for the second header, if it exists then apply the ui-scrollfix directive to it.

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

Upvotes: 0

Related Questions