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">
1
  • you have to manually trigger the digest cycle using $apply() . Commented Aug 3, 2017 at 13:34

3 Answers 3

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;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

i read somewhere that in angularjs the element is permanently hide but in media queries its just not visible but remain there. so the best way is to use angularjs .
but thanks for the answer. It worked. i waste half of my day on it. and the solution is only of 1 line.
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()

    } });});

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.