从指令获取元素样式-随机失败

Get element style from directive - Randomly fails

本文关键字:随机 失败 样式 元素 指令 获取      更新时间:2023-09-26

在一个角度指令中,我希望获得一些样式(例如:backgroundImage)来存储它以备将来使用。我有以下代码:

angular.module('myApp')
    .directive('myDirective', function() {
        return {
            restrict: 'A',
            terminal: true,
            link: function(scope, element, attrs) {                                 
                // examples of how get it
                console.log(element.css('background-image'));
                console.log(window.getComputedStyle(element[0]).backgroundImage);
            }
         };
     });

大多数时候,我成功地获得了backgroundImage值,但有时我只得到null的值。然后我刷新页面并再次成功获取值。如何从指令中获取样式属性而不出现此问题?

任何提示或建议都将不胜感激。感谢

您可以通过等待$viewContentLoaded事件来确保在加载所有内容后读取css:

angular.module('myApp')
    .directive('myDirective', function() {
        return {
            restrict: 'A',
            terminal: true,
            link: function(scope, element, attrs) {                                 
                scope.$on('$viewContentLoaded', function() {
                    console.log(element.css('background-image'));
                    console.log(window.getComputedStyle(element[0]).backgroundImage);
                });
            }
         };
     });