コントローラーからサイズ変更時にAngularJSのウィンドウ幅を取得するにはどうすればよいですか? 質問する

コントローラーからサイズ変更時にAngularJSのウィンドウ幅を取得するにはどうすればよいですか? 質問する

コントローラーからサイズ変更時にAngularJSのウィンドウ幅を取得するにはどうすればいいですか?取得できるようにして、いくつか表示できるようにしたいdivです<div ng-if="windowWidth > 320">

最初のページの読み込み時に windowWidth を取得できますが、サイズ変更時には取得できません...

'use strict';

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

app.controller('mainController', ['$window', '$scope', function($window, $scope){
	var mainCtrl = this;
	mainCtrl.test = 'testing mainController';
  
    // Method suggested in @Baconbeastnz's answer  
    $(window).resize(function() {
      $scope.$apply(function() {
        $scope.windowWidth = $( window ).width();
      });
    });
  
    /* this produces the following error
    /* Uncaught TypeError: mainCtrl.$digest is not a function(…)
    angular.element($window).bind('resize', function(){
        mainCtrl.windowWidth  = $window.innerWidth;
        // manuall $digest required as resize event
        // is outside of angular
        mainCtrl.$digest();
    });  
    */
}]);

// Trying Directive method as suggested in @Yaser Adel Mehraban answer.
/*app.directive('myDirective', ['$window', function ($window) {
     return {
        link: link,
        restrict: 'E'            
     };
     function link(scope, element, attrs){
       angular.element($window).bind('resize', function(){
           scope.windowWidth = $window.innerWidth;
       });    
     }    
 }]);*/
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<body ng-app="app" ng-controller="mainController as mainCtrl">
	<p>{{mainCtrl.test}}</p>
	<hr />
    <p ng-if="windowWidth > 600">The window width is {{windowWidth}}</p>
    <div my-directive ng-if="windowWidth > 320">It works!</div>
</body>

私は見るこの答えディレクティブ内から取得する方法は説明されていますが、コントローラー内から動作させるにはどうすればよいのでしょうか?

ベストアンサー1

最善の方法は、ディレクティブを使用してウィンドウのサイズ変更イベントを監視することです。

'use strict';

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

app.directive('myDirective', ['$window', function ($window) {

     return {
        link: link,
        restrict: 'A'           
     };

     function link(scope, element, attrs){

       angular.element($window).bind('resize', function(){
           scope.windowWidth = $window.innerWidth;
       });    
     }    
 }]);

これを div で使用します:

<div my-directive ng-if="windowWidth > 320">

こちらは動作中のプランカー

おすすめ記事