簡體   English   中英

AngularJS觀察div大小

[英]AngularJS observing div size

我仍在學習AngularJS的工作方式,並致力於$watch工作方式。 我有這種情況,我想觀察div.id="area"的尺寸。 由於我正在觀察尺寸,因此我計划在值的任何更改( clientWidthclientHeight )時觸發一個函數。

到目前為止,據我對$watch了解,我得到的是:

$scope.browser = {
    width: document.getElementById("area").offsetWidth,
    height: document.getElementById("area").offsetHeight
};
console.log($scope.browser);
$scope.$watch("browser", function(newValue, oldValue) {
    console.log("changed from: " + oldValue.width + " to " + newValue.width);
}, true);

有什么想法可以讓手表正常工作嗎?

問題是,您正在觀看不可變的對象。 創建$scope.browser時,將讀取一次widthheight 因為這些值永遠不會更新,所以$watch將永遠不會觸發您的回調。

有幾種解決方案:

1)您可以監視函數值而不是對象值,例如:

$scope.$watch(function() {
   return {
     width: document.getElementById("area").offsetWidth,
     height: document.getElementById("area").offsetHeight
   }
}, function(newValue, oldValue) {
   console.log("changed from: " + oldValue.width + " to " + newValue.width);
}, true);

這效率極低(訪問DOM的速度很慢),但是有可能(如果無法在您的情況下應用其他解決方案)。

2)查找#area更改尺寸的情況。 瀏覽器是否調整大小? 是jQuery /另一個3D派對腳本嗎? 例如,要攔截窗口調整大小,可以使用以下指令:

.directive('windowResize',['$parse', '$timeout', function($parse, $timeout){
  return function($scope, $element, $attrs) {
    var fn = $parse($attrs.windowResize);
    $(window).on('resize', function(){
      $scope.$apply(function() {
        fn($scope);
      });
    });
}])

//template
<div id="area" window-resize="onWindowResize()"></div>

如果使用其他腳本,則可以從DOM send事件獲取范圍或直接修改$scope.browser

//jquery script
var dimensions = {widht: newWidht, height: newHeight};
updateAreaDimensions(dimensions);
//broadcast event, decoupling this script from scope's code
$('body').scope().$broadcast('areaDimensionsUpdated', dimensions);
//or modify your $scope.browser object
$('body').scope().browser = dimensions;

如果發生事件,您可以在自己的范圍內收聽:

$scope.$on('areaDimensionsUpdated', function($event, args) {
  //
});

試試吧..

scope.browser = {
    width: document.getElementById("area").offsetWidth,
    height: document.getElementById("area").offsetHeight
};

$scope.$watch(function() {
    console.log("changed from: " + $scope.browser.width + " to " +  $scope.browser.width);
});

嘗試這個。 它更類似於您的要求。 代替div的是窗口的尺寸。

function Dimensions($scope){
    $scope.docWidth = 0;
    $scope.docHeight = 0;

}

http://jsfiddle.net/kapilgopinath/ayVW6/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM