2017-08-03 92 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>

相關問題