javascript - 指令并不总是在页面加载时触发

标签 javascript angularjs

我有一个指令,可以获取特定元素的高度并将其应用于另一个元素。

但由于某种原因,它并不总是在页面加载时触发。我认为也许在某些情况下元素加载时间太长,并且仅在完全加载后才处理它可能是一个更明智的想法。它似乎在页面调整大小(有时)方面效果很好。

这是为什么?我该如何解决它?

例如:

// grab information of div height here    

<div class="col-sm-6" id="left-photos" element-size key="leftPhotoSize"></div>

// apply it here

<div class="col-sm-6" ng-style="{ 'height': leftPhotoSize.height + 30 + 'px' }"></div>

指令

angular.module('adsomaApp')
  .directive('elementSize', function ($timeout, $window) {
    return {
      restrict: 'A',
      link: function (scope, element, attrs) {
        var height, width;
        var measure = function () {
          height = element[0].offsetHeight;
          width = element[0].offsetWidth;
          if (attrs.key) {
            scope[attrs.key] = {
              height: height,
              width: width
            };
          }
          scope.elementSize = {
            height: height,
            width: width
          };
        };

        $timeout(function () {
          measure();
        });
        $window.load(function() {
          measure();
        });
        angular.element($window).bind('resize', function () {
          measure();
          scope.$digest();
        });
      }
    };
  });

最佳答案

您能否将您的测量函数放入 $watch 函数中,然后加上scope.$apply()。

关于javascript - 指令并不总是在页面加载时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48245737/

相关文章:

javascript - Radiobuttons ng-checked 默认情况下不显示 div 并且仅在 onclick 时起作用

javascript - 执行前不显示 AngularJS 代码

javascript - 在 Angular 1.4 中应该手动调用 $digest 吗?

javascript - 验证指令代码在 ng-repeat 中的每个项目上执行

javascript - React Native 占位符图标

javascript - html 输入字段自动填充浏览器表单中保存的用户名

javascript - 如何在 JavaScript 中设置 session 变量?

javascript - $project 以外的方法在 $lookup 和 $unwind 之后限制 MongoDB View 中的数据

javascript - 向继承类添加非继承函数 - Javascript

javascript - 如何根据对象数组查询docpad中的文档