Nat
Nat

Reputation: 3077

How to make an angularjs directive aware of whether or not it is visible on the page

I have some custom directives, which control custom validations.

These directives may be hidden by an ngShow or ngHide directive, on its own element or an ancestor element.

How can I make my directive aware of whether or not it is hidden? (so that when another controller asks about its contents it won't report validation errors)

I guess it's possible to have a method on the directive's controller that checks whether the directive's element, or any of its ancestor elements have an ng-show/hide attribute set with an expression that evaluates within its own scope so as to hide it... But this would require an undesirable quantity of logic and dom access (slow), and so I'm hoping there's a better way.

Upvotes: 2

Views: 2143

Answers (2)

SoluableNonagon
SoluableNonagon

Reputation: 11755

if your directive is declared somewhat like this:

<mydir ng-show='showThisDir'></mydir>

then it is linked to a scope variable like so:

$scope.showThisDir = true;

then add data to the scope of your directive, so it should be something like this:

.directive('mydir', function() {
    return {
      restrict: 'E',
      scope: {
        someData: '=info',
        isShown: '='
      },
      template: 'some html'
    };

});

and add it in your declaration like so:

<mydir ng-show='showThisDir' is-shown='showThisDir'></mydir>

now your directive is aware of whether it is shown

another way could be:

.directive('mydir', function() {
    function link(scope, element, attrs) {
        var display = element.css('display'); 
        // whether it is displayed, but this would get more complicated 
        // as you need to set watchers when you changed data and
        // recalculate the display value
    },
    return {
      restrict: 'E',
      scope: {
        someData: '=info',
      },
      template: 'some html'
    };

});

Upvotes: 2

Fresheyeball
Fresheyeball

Reputation: 30015

I would prefer an approach where the directive does not need to know what on scope may be showing or hiding its ancestor, and check the element directly to determine if its visible.

if (element.offsetWidth === 0 || element.offsetHeight === 0) return false;

The above script will return false if the element is hidden for any reason, wether it be ng-show on the element itself, on an ancestor or css or otherwise.

Upvotes: 2

Related Questions