2015-10-16 64 views
0

我正在監視CSS樣式並更新基於該CSS樣式值的範圍內的變量。它第一次工作,但是當瀏覽器調整大小時,作用域得到更新,但ng樣式不會使用新的作用域參數更新。更新範圍時,ng-style變量不更新

JS:

.directive('monitorStyle', function() { 
     return { 
      link: function(scope, element, attrs) { 
       scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle); 
       angular.element(window).on('resize', function() { 
        scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle); 
       }); 

      } 
     } 
    }) 

HTML:

<p class="text" monitor-style="font-size" update-variable="textHeight">Press "<img class="mini up" src="img/select-arrow.png" src="Up" ng-style="{'height': textHeight}"> 

我想,因爲這是人推薦做這個控制器之外。爲什麼在範圍更新時ng樣式不會更新?

+0

您是否嘗試過使用$(窗口).resize而不是角?如果你想通過角度實現這一點,那麼下面的鏈接將幫助你。 http://stackoverflow.com/questions/23044338/window-resize-directive –

+0

也許這個答案可能會幫助你http://stackoverflow.com/a/25111105/2353403 –

+0

謝謝,Damnien回答如下。訣竅是添加範圍。$ apply();在指令 – user2476265

回答

2

窗口事件不是一個角度事件,所以角度不知道他必須更新模型/範圍。你必須添加範圍$適用()來告訴角度來刷新它。當你的模型與像$ HTTP,$超時角事件更新

angular.element(window).on('resize', function() { 
    scope[attrs.updateVariable] = $(element).css(attrs.monitorStyle); 
    scope.$apply(); 
}); 

數據bindig只適用,NG-單擊,...

關於它的偉大的文章:http://jimhoskins.com/2012/12/17/angularjs-and-apply.html

+1

中調整大小事件的內部注意:我正在嘗試這個,但應用範圍。$ apply();在angular.element(窗口)之外調整大小,它給我提供了$ digest進行中的錯誤,您可以調用範圍。$ apply too early – user2476265

0

喲,我做了這個生病的解決方案。

所以,如果你想觀看的風格(甚至是一個特定的元素在他們的陣列),然後把它們的值,你可以用這個$範圍JS:

.directive('monitorStyle', function($timeout) { 
    return { 
     link: function(scope, element, attrs) { 
      function addToScope() { 
       var updateVariable = attrs.updateVariable.split(','); 
       var monitorStyle = attrs.monitorStyle.split(','); 
       for (var i = 0; i < updateVariable.length; i++) { 
        scope[updateVariable[i]] = $(element).css(monitorStyle[i]); 
       } 
      } 
      addToScope(); 
      angular.element(window).on('resize', function() { 
       addToScope(); 
       scope.$apply(); 
      }); 
     } 
    } 
}) 

,並將其應用是這樣的:

<h2 monitor-style="font-size,line-height" update-variable="headerHeight,headerLineHeight"> 

這將更新$範圍初始化和窗口大小調整。你當然可以修改它以達到你自己的目的。

每次$範圍變化,你可以更新其他的風格是這樣的:

<div ng-style="{'height': headerHeight, 'line-height': headerLineHeight}">