在子元素的指令中获取CSS属性

时间:2017-11-20 20:04:23

标签: javascript css angularjs dom

我目前正在遍历指令附加到的元素的子元素,并为mouseup和mousedown添加回调:

    var dragDroppables = element[0].children;

    for (var elementIdx = 0; elementIdx < dragDroppables.length; elementIdx++) {
        var bindElement = dragDroppables[elementIdx];

        var elementID = bindElement.attributes['id'].value;

        if(elementID == "DragDroppable") {

            var bindElementAngular = angular.element(bindElement);

            bindElementAngular.on('mousedown', function() {
                bindElementAngular.css('background-color', 'rgb(17, 83, 252)');            
                elementHeldDown = bindElementAngular;
                isElementHeldDown = true;

                //window and angular.window are both undefined in this case
                var style = angular.window.getComputedStyle(bindElementAngular);         
                heldDownElementWidth = parseInt(style.getPropertyValue('width'));
                heldDownElementHeight = parseInt(style.getPropertyValue('height'));     
            });
            bindElementAngular.on('mouseup', function () {
                bindElementAngular.css('background-color', 'rgb(73, 122, 255)');
                isElementHeldDown = false;
            });
          }
       }
    }

现在它抱怨窗口对象未定义。当我在控制器中有这个功能直接获取窗口对象(没有从角度对象调用它)工作正常。现在,它在指令中似乎不再起作用了。如何从指令内的任意DOM对象获取CSS属性?

1 个答案:

答案 0 :(得分:0)

尝试在指令

中注入窗口对象
directives.insertStyle = [ "$window", function($window){
    return {
        link: function(scope, element, attrs) {
            var elementStyleMap = $window.getComputedStyle(element[0], null);

        }
    }   
}];