Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Element Style from Angular directive

Tags:

angularjs

I'm sure this is going to be a "dont do that!" but I am trying to display the style on an angular element.

<div ng-repeat="x in ['blue', 'green']" class="{{x}}">
        <h3 insert-style>{{theStyle['background-color']}}</h3>
</div>

Result would be

<div class='blue'><h3>blue(psudeo code hex code)</h3></div>
<div class='green'><h3>green(psudeo code hex code)</h3></div>

I basically need to get the style attributes and display them.

Directive Code...

directives.insertStyle = [ function(){
    return {
       link: function(scope, element, attrs) {
           scope.theStyle = window.getComputedStyle(element[0], null);
       }
}   
}];

Fiddle example: http://jsfiddle.net/ncapito/G33PE/

like image 895
Nix Avatar asked Jan 18 '26 10:01

Nix


1 Answers

My final solution (using a single prop didn't work, but when I use the whole obj it works fine)...

Markup

<div insert-style  class="box blue">
  <h4 > {{ theStyle['color'] | toHex}} </h4>
</div>

Directive

directives.insertStyle = [ "$window", function($window){
    return {
        link: function(scope, element, attrs) {
            var elementStyleMap = $window.getComputedStyle(element[0], null);
            scope.theStyle = elementStyleMap
        }
    }   
}];
like image 198
Nix Avatar answered Jan 21 '26 02:01

Nix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!