h01001000
h01001000

Reputation: 281

Accessing a style property while using AngularJS to set styles dynamically

I am trying to let the user set styles dynamically, but I also want to grab the values of certain styles. For example, I want to check if the user sets the color of an H1 element to 'orange'.

My HTML

<body ng-controller="mainController">    
    <h1 id="myH1">Hello World!</h1>

    <textarea ng-model="outputCss"></textarea>

    <style media="screen" type="text/css">
      {{outputCss}}
    </style>   
</body>

My Javascript, in mainController

var myH1Style = document.getElementById('myH1').style;

$scope.$watch('outputCss', function(newValue, oldValue){
    if (myH1Style.color == "orange"){
      alert("Nice work!");
    }
    console.log(myH1Style.color);
});

Example User Input

#myH1 {
color: orange;
}

h1 {
font-weight: 900;
}

The problem is, the if condition can never be met, and the console log is always empty. How can I read CSS properties that are added using this method?

Upvotes: 0

Views: 226

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

Your question is basically two questions:

  1. How do I compare colors? (Sadly, the answer here is that it's ugly, the value you get back is probably not in the format in which it was applied, so you might get "orange" or "rgb(255, 165, 0)" or "rgb(255,165,0)" or "rgba(255, 165, 0, 1)"...)

  2. How do I get the styles as applied by CSS rules?

The combination of the answers to those questions answers your question. Basically, you need to use getComputedStyle(element) (or element.currentStyle on old IE) to get the computed style (.style only gives you the styles directly applied to the element), and the value you get back may well not be in the format that it is in the stylesheet (but in some browsers may be, hence...ugly).


Side note: A hardcoded id value is a red flag. Use ref instead.

Upvotes: 1

Koushik Chatterjee
Koushik Chatterjee

Reputation: 4175

even before telling that you are comparing the colors in wrong manner, first of all document.getElementById('myH1').style; will a return the inline style, not the style applyed by CSS rules. and you are dynamically changing CSS rule and watching the inline style against that.

Upvotes: 0

Related Questions