使用angularjs获取div宽度高度

时间:2015-10-29 14:12:30

标签: html angularjs angularjs-directive

这是我的指示。我在控制台中获得了控制台(“你好”)的值,但我没有得到我添加指令调整大小的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}}

1 个答案:

答案 0 :(得分: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');
              });
          }
      }
}

});