我可以在初始页面加载时获取窗口宽度,但在调整大小时无法获取-6ren">
gpt4 book ai didi

angularjs - 如何从 Controller 调整大小时获取 angularJS 中的窗口宽度?

转载 作者:行者123 更新时间:2023-12-02 21:47:05 25 4
gpt4 key购买 nike

如何从 Controller 调整大小时获取 angularJS 中的窗口宽度?我希望能够获得它,以便我可以显示一些 div<div ng-if="windowWidth > 320">

我可以在初始页面加载时获取窗口宽度,但在调整大小时无法获取...

'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>

我在 this answer 中看到他们解释了如何从指令中获取它,但如何让它在 Controller 中工作?

最佳答案

最好的方法是使用指令并监 window 口的调整大小事件:

'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">

这是一个工作 plunker .

关于angularjs - 如何从 Controller 调整大小时获取 angularJS 中的窗口宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41175143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com