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

标签 javascript jquery angularjs

在 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/

相关文章:

javascript - Angular js : Display an iframe in a pop up and see an empty frame

javascript - Typescript "Element implicitly has an ' any' 类型,因为类型 'Rank' 的表达式不能用于索引类型 'IPowerCards' "

javascript - += 的异步函数

javascript - Moment.js 其他时区的本地时间转为 UTC

javascript - JQuery .keyup() 问题

AngularJS 指令隔离范围不起作用

javascript - 为什么 js 变量在桌面上的 JQuery 移动多页面模板页面上持久存在,但在移动设备上却不然

javascript - 如何使用 jQuery 将光标从指针更改为手指?

javascript - 从 Angular 2 组件调用 JQuery 方法

javascript - Angularjs - 将指令中的值绑定(bind)到 ng-show/hide 文档中的任何位置