角度指令$ watch sibling height change

时间:2015-09-09 03:16:34

标签: angularjs angularjs-directive

我正在尝试侦听兄弟元素的高度变化,但到目前为止,我无法使其工作..... element[0].nextElementSibling.clientHeight在初始化时返回正确的值但不更新....

(function() {
  'use strict';
  angular.module('someApp').directive('heightdir', function($window) {
    return {
      link: function(scope, element) {

        // Adjust height.
        scope.calcCommentsHeight = function() {
          var _h;
          if ($window.innerWidth > 768) {
            _h = $window.innerHeight - 222 - element[0].nextElementSibling.clientHeight;
            $(element).css('height', _h + 'px');
          }
        };

        // Sibling height change.
        scope.$watch((function() {
          return element[0].nextElementSibling.clientHeight;
        }), (function(newValue, oldValue) {
          if (newValue !== oldValue) {
            console.log(newValue);
          }
        }), true);

        // window resize.
        angular.element($window).bind('resize', function() {
          scope.calcCommentsHeight();
        });

        // Init.
        scope.calcCommentsHeight();
      }
    };
  });

}).call(this);

1 个答案:

答案 0 :(得分:0)

一个选项:创建一个服务来存储一个元素值,然后在第二个元素上读取该服务。

angular.module('whatever.module', []).service('ElementHeight', function() {
    var height = 0;
    return {
      height: function() { return height; },
      setHeight: function(newHeight) { height = newHeight }
    }
});

伪代码示例:

function ThisController(ElementHeight) {
    // set it to the height of the element, how depends on what you're doing.
    ElementHeight.setHeight(999,999);

    // to get the height
    newHeight = ElementHeight.height;
}