Search code examples
angularjsangular-ng-if

AngularJS - ng-if - show when body has a class


I want to show/hide an element using ng-if

e.g. I would like to show an element if body has got specific class

I've tried the following, but no success - is this even valid expression?

<div ng-if="document.querySelector('body').className.indexOf('bodyHasThisClass') >= 0"></div

Any suggestions much appreciated. Here is a plunk example: http://plnkr.co/edit/kzXXg0sne8nyQZuufao7?p=preview


From AngularJS docs: https://docs.angularjs.org/guide/expression

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.


Solution

  • How about adding a controller to your directive

    app.directive('wrapperDirective', function() {
    return {
        restrict: 'A',
        templateUrl: 'wrapper-directive.html',
        replace: true,
        transclude: true,
        controller: function($scope){
          $scope.a = (document.querySelector('body').className.indexOf('bodyHasThisClass')>= 0)? true : false;
          $scope.b = (document.querySelector('body').className.indexOf('noSuchClass')===-1)? true:false;
    
        }
    };
    });
    

    And in template:

    <div ng-if="a==true">
        visible if body has class bodyHasThisClass
    </div>
    <div ng-if="b==false">
        this should be hidden
    </div>