Angularjs - the ng-class directive is not working

Asked

Viewed 363 times

0

I’m trying to apply this class to is when I roll the page to pin my menu to the top of the screen, but the class is not being set:

<div class="page-header-menu" ng-class="{'fixed':(document.documentElement.scrollTop > 74)}">
    <!-- aplicação-->
</div>

I’m using version 1.2.30.
My thanks to those who answer.

  • Put this here {{(document.documentElement.scrollTop > 74)}}, in the view, does it work? I mean, it shows something?

  • creates in your controller a $Scope variable that loads the result of document.documentElement.scrollTop and makes the ng-class conditional using this variable. with me it worked so.

1 answer

0

It is not good practice to access the document directly inside an angular component, but to solve its problem follows code example below.

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.a = 'aaa';
  $scope.fixElement = function(){
    return document.documentElement.scrollTop > 74
  }
})
.fixed {
  position: fixed;
  top: 100px;
  color: red;
 }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div ng-class="{'fixed': fixElement()}">{{a}}</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.