gpt4 book ai didi

javascript - Controller 中的窗口调整大小设置变量不起作用

转载 作者:行者123 更新时间:2023-11-30 15:41:55 24 4
gpt4 key购买 nike

在 Angular 中,如果窗口宽度超过某个阈值,我会观察窗口大小并更改 Controller 上的“设备”变量:

 var myModule = angular.module("MyApp", [])
.controller('MyController', function(UseHttp){

// store reference of "this"
var self = this;

function setDevice(){
var wWidth = $(window).width();
var theDevice;

if (wWidth <= 991 && wWidth > 767) {
theDevice = "narrow desktop";
} else if (wWidth <= 767 && wWidth > 620) {
theDevice = "iPad";
} else if (wWidth <= 620 && wWidth > 500) {
theDevice = "largeMobile";
} else if (wWidth <= 500 && wWidth > 320) {
theDevice = "mediumMobile";
} else if (wWidth <= 320) {
theDevice = "smallMobile";
} else {
theDevice = "desktop";
}

self.device = theDevice;
}

//self.device gets set on window resize
$(window).resize(function(){
setDevice();
$scope.$apply(); //but where do I store the var $scope?
});

//self.device gets set right away
setDevice();

}).service('UseHttp', function($http) {....

但出于某种原因,当我更改窗口大小以达到新阈值时, View 上的此 p 标记不会更新(但它会显示初始“设备”)

 <article ng-controller="MyController as myCtrl" class="content-wrapper">
<p>{{myCtrl.device}}</p>

最佳答案

通过在调整大小事件中设置设备,当模型更新时,不会触发摘要循环。您需要使用 $scope.$apply() 手动执行此操作,如下所示:

$(window).resize(function() {
setDevice();
$scope.$apply();
});

关于javascript - Controller 中的窗口调整大小设置变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40666540/

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