控制器中的窗口调整大小设置变量不起作用

时间:2016-11-17 22:55:16

标签: javascript jquery angularjs

在Angular中,我正在观察窗口大小并更改“设备”。如果寡妇宽度超过某个阈值,控制器上的变量:

 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) {....

但由于某种原因,当我更改窗口大小以达到新阈值时,视图上的此p标记不会更新(但它会显示初始设备&#39;)

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

1 个答案:

答案 0 :(得分:2)

通过在resize事件中设置设备,更新模型时没有任何内容触发摘要周期。您需要使用$ scope手动执行此操作。$ apply()如下所示:

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