2016-11-17 60 views
1

在角设定变量,我留意窗口的大小和在控制器上改变“装置”变量如果寡妇宽度超过某一阈值:窗口调整大小控制器不工作

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标签不更新(但它确实表明了最初的“设备”)

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

回答

2

通过在resize事件没有设置设备正在更新模型时触发摘要循环。你需要用$范围做手工$适用()这样的:

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

我建议做$从setDevice()调用内申请(),因为这实际上是范围突变哪里发生。 –

+0

@YonaAppletree - 这样做的问题是,当摘要已经在进行时,最初调用setDevice()。 – jbrown

+0

这个唯一的问题 - 在窗口调整大小我得到错误:'找不到变量:$ scope'。我更新了我的代码以显示我的完整控制器。我在哪里存储$ scope变量? – NewToJS