1

I am new in angularjs. I searched a lot to hide some html element on body resize but did't work. here is my controller code.

var app = angular.module('studentPage',[]);

    app.controller ('studentController',function($scope, $window) {

    var appWindow = angular.element($window);

    appWindow.bind('resize', function () {
        if($window.innerWidth < 600){
            alert("hello");
            $scope.ohh = true;
        }
  });

});

and here where i use ng-show

<div id="sidebar-wrapper" ng-show="ohh">

3 Answers3

3

If you want to achieve this using AngularJS, you need to relaunch the digest cycle using $scope.$apply().

appWindow.bind('resize', function () {
    if($window.innerWidth < 600){
        $scope.ohh = true;
        $scope.$apply();
    }

});

Anyway, I think a cleaner way to do that is using CSS media queries:

@media only screen and (max-width: 599px) {
    #sidebar-wrapper {
        display: none;
    }
}
Mistalis
  • 17,793
  • 13
  • 73
  • 97
0

You have to manually trigger the digest cycle using $apply() function , since what you are doing is out of angular context.Try the below code.

var app = angular.module('studentPage',[]);

app.controller ('studentController',function($scope, $window) {

var appWindow = angular.element($window);

appWindow.bind('resize', function () {
    if($window.innerWidth < 600){
        alert("hello");
        $scope.ohh = true;
        $scope.$apply()

    } });});
Anurag
  • 643
  • 1
  • 11
  • 28
0

You have to apply the scope changes by calling $scope.$apply().:-

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $window) {

  var appWindow = angular.element($window);
  $scope.ctrl = {};
  $scope.ctrl.ohh = false;
  appWindow.bind('resize', function() {
    console.log($window.innerWidth);
    if ($window.innerWidth < 600) {
      $scope.ctrl.ohh = true;
      $scope.$apply()
    }
  });
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>

<body>

  <div ng-app="myApp" ng-controller="myCtrl">
  <h1>THis is main content</h1><br>
    <div id="sidebar-wrapper" ng-show="ctrl.ohh">This is shown after window width is less than 600
    </div>
  </div>
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36