Angular指令$watch兄弟姐妹的高度改变



我试图倾听兄弟元素的高度变化,但到目前为止,我不能得到这个工作.....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);

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

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;
}

最新更新