2017-08-03 104 views
1

我是angularjs中的新成员。我搜索了很多隐藏一些HTML元素的身体调整大小,但没有工作。这是我的控制器代码。如何隐藏屏幕上的某些元素在angularjs中调整大小

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; 
     } 
    }); 

}); 

和在这些地方如果想要实现这个使用AngularJS我使用NG-显示

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

你必须手动触发使用$消化周期apply()。 – talentedandrew

回答

3

,您需要使用$scope.$apply()重新发起digest cycle

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

});

无论如何,我认为一个更清洁的方式做到这一点是使用CSS media queries

@media only screen and (max-width: 599px) { 
    #sidebar-wrapper { 
     display: none; 
    } 
} 
+0

我在angularjs的某个地方读过元素永久隐藏,但在媒体查询中它只是不可见,但仍然存在。所以最好的方法是使用angularjs。 –

+0

但谢谢你的答案。有效。我浪费了我一天的一半时间。而解决方案只有1行。 –

0

您必须手动触发使用$ apply()函数的消化周期,因为你在做什么超出角请尝试下面的代码。

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() 

    } });}); 
0

你必须通过调用$范围应用范围的变化$适用(): - 。

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>

相关问题