【问题标题】:Angular nested directive ordering角度嵌套指令排序
【发布时间】:2014-12-23 19:15:48
【问题描述】:

我很难找到有关指令顺序及其 css 属性更新的任何信息。

例如,我有两个指令,一个用于将元素设置为全屏高度,另一个用于垂直对齐内容。

app.directive('fullscreenElement', function() {
    return { 
        restrict: "A",
        link: function(scope,element,attrs){    
            $(element).each(function(){
                $(this).css('height', $(window).height());
            }); 
        }
    };
});

app.directive('alignVertical', function() {
    return { 
        restrict: "A",
        link: function(scope,element,attrs){
            var height = $(element).height();
            var parentHeight = $(element).parent().height();
            var padAmount = (parentHeight / 2) - (height / 2);
            $(element).css('padding-top', padAmount);
        }
    };
});

它们都独立工作,问题是当它们嵌套时,align-vertical 指令不起作用,我假设这是因为尚未设置 css 高度?我如何确保在 alignVertical 指令运行之前设置它?任何以更角度的方式编写这两个指令的提示将不胜感激。

这行得通:

<header style="height:800px">           
    <div align-vertical>
            this content is centered vertically as expected
    </div>
</header>        

这不起作用(即使标题高度现在是全屏,内容也不会垂直居中):

<header fullscreen-element>         
    <div align-vertical>
            the header element is now fullscreen height but this content is *not* centered vertically
    </div>
</header>

谢谢

【问题讨论】:

    标签: css angularjs angularjs-directive


    【解决方案1】:

    想出了一个解决方案,把它贴在这里,以防有人觉得它有帮助。

    诀窍是使用 scope.watch 和 scope.evalAsync 来监控父容器的高度变化,并在渲染完成后运行它们。

    app.directive('alignVertical', function() {
    return {
        link: function($scope, element, attrs) {
            // Trigger when parent element height changes changes
            var watch = $scope.$watch(function() {
                return element.parent().height;
            }, function() {
                // wait for templates to render
                $scope.$evalAsync(function() {
                    // directive runs here after render.
                    var that = $(element);
                    var height = that.height();
                    var parentHeight = that.parent().height();
                    var padAmount = (parentHeight / 2) - (height / 2);
                    that.css('padding-top', padAmount); 
                });
            });
        },
    };
    });
    

    【讨论】:

      猜你喜欢
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2013-12-28
      • 1970-01-01
      相关资源
      最近更新 更多