Search code examples
angularjsscrollng-hide

ng-hide isn't working with scroll event


I have been trying to use ng-hide on scroll events. I am using it like this

angular.module('myApp')
.controller('MyCtrl', function ($scope,$window) {

$scope.name={
  White:false,
  Crimson:true
}

  $scope.swapColor=function(){
    if($window.scrollY>648){
      console.log("Hide White");
        $scope.name.White=true;
        $scope.name.Crimson=false;
    }
    else{
      console.log("Hide Crimson");
      $scope.name.White=false;
      $scope.name.Crimson=true;
    }
  }

  angular.element($window).on('scroll',$scope.swapColor);

});

and in index.html I have this

<div ng-hide="name.White"><img src="images/nameWhite.png" class="img-responsive nameWhite"></div>
<div ng-hide="name.Crimson"><img src="images/nameCrimson.png" class="img-responsive nameCrimson"></div>

The thing is the function gets called on scroll as I can see the Hide Crimson and Hide White in the console but the White div does not hide and crimson one does not appear.

Any help would be appreciated!!


Solution

  • Here is a working example of your problem

    Try this

    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    	<script type="text/javascript">
    		var app = angular.module("myApp", []);
    		app.controller("myCtrl", function($scope,$window) {
    			$scope.name={
    				White:false,
    				Crimson:true
    			}
    
    			$scope.swapColor=function(){
    				if($window.scrollY>648){
    					//console.log("Hide White");
    					$scope.name.White=true;
    					$scope.name.Crimson=false;
    				}
    				else{
    					//console.log("Hide Crimson");
    					$scope.name.White=false;
    					$scope.name.Crimson=true;
    				}
    				if (!$scope.$$phase) {
    					$scope.$apply();
    				}
    			}
    
    			angular.element($window).on('scroll',$scope.swapColor);
    		});
    
    
    	</script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl" style="height: 2470px">
    
    	<div ng-hide="name.White" style="position: fixed;">
    		IMG 1
    	</div>
    	<div ng-hide="name.Crimson" style="position: fixed;">
    		IMG 2
    	</div>
    </body>
    
    
    </html>