2015-10-29 183 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