2015-10-29 180 views
0

這是我的指令。我越來越控制檯在我的控制檯中的值(「你好」),但我沒有得到高度或DIV的寬度,而我已經添加了指令調整使用angularjs獲取div寬度高度

'use strict'; 
app.directive('resize', function ($window) { 

    console.log("hello"); 
    return function (scope, element) { 
     restrict: 'E' 
     var w = angular.element($window); 
     console.log(w); 

     scope.getWindowDimensions = function() { 
      return { 
       'h': w.height(), 
       'w': w.width() 
      }; 
     }; 
     scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) { 
      scope.windowHeight = newValue.h; 
      scope.windowWidth = newValue.w; 
      console.log(scope.windowHeight); 
      console.log(scope.windowWidth); 

      scope.style = function() { 
       return { 
        'height': (newValue.h - 100) + 'px', 
        'width': (newValue.w - 100) + 'px' 
       }; 
      }; 

     }, true); 

     w.bind('resize', function() { 
      console.log(w.bind()) 
      scope.$apply(); 
     }); 
    } 
}) 
下面

在我的div

<div data-ng-show="GameHeaderScreen.Start" class="head" ng-style="style()" id="playid" resize>window.height: {{windowHeight}} 
    <br />window.width: {{windowWidth}} 
+0

這不是你如何聲明一個指令。 – cgTag

+0

當'scope。$ digest()'被調用並且被監視的變量值已經改變時,監視被觸發。元素大小更改時不會調用摘要。所以你不能監控'$ watch'的寬度變化。 – karaxuna

+0

@ karaxuna45:那麼我現在應該添加什麼? – shank

回答

1

您必須遵循需要鏈接功能的指令模式。

此外,當範圍被銷燬時,您需要解除對窗口的監聽。

app.directive('resize', function ($window) { 

     var w = angular.element($window); 
     console.log(w); 

     return { 
      restrict: 'E', 

      // declare a link function 
      link: function(scope,element) { 

      scope.getWindowDimensions = function() { 
       return { 
        'h': w.height(), 
        'w': w.width() 
       }; 
      }; 

      scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) { 
        scope.windowHeight = newValue.h; 
        scope.windowWidth = newValue.w; 

        scope.style = function() { 
         return { 
         'height': (newValue.h - 100) + 'px', 
         'width': (newValue.w - 100) + 'px' 
         }; 
        }; 
       }, true); 

       var resize = w.bind('resize', function() { 
        scope.$apply(); 
       }); 

       // remove the global event!! 
       scope.$on('$destroy', function() { 
        w.unbind('resize'); 
       }); 
      } 
     } 
} 

}); 
+0

@shank我正在發佈一個角度庫,處理調整大小事件的過程,如你的例子:https://github.com/thinkingmedia/thinkingmedia-ui – cgTag

+0

@shank試試這個:http://www.learn-angular .org/ – cgTag

+0

@shank讀ng-book也https://thinkster.io/a-better-way-to-learn-angularjs – murli2308