angularjsangularjs-bindings

AngularJS: trying to create a style value by combining a variable and "px"


I've made a program that allows a user to write text on a "white board" and change color in real time. I'm now trying to give the user the ability to change font-size as well. How could I combine the "writing_size" variable with the characters "px" to form a value for "font-size"?

    <!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>


<title>AngularJS Whiteboard</title>
</head>

<body>

<div ng-app="">



<textarea name="message" rows="10" cols="30" ng-model="writing">
</textarea>
<span>    Marker color: <input type = "text" size = "7" ng-model="marker_color"></span>
<span>    Writing size: <input type = "text" size = "7" ng-model="writing_size"></span>

<br>
<br>

<div id = "whiteboard" ng-bind="writing" ng-style="{ color : marker_color, font-size: {{writing_size + 'px'}} }">   
</div>

<div id = "test">
{{ writing_size + "px"}}
</div>

</div>

</body>
</html>

Solution

  • First problem: the font-size key must not be used without apostrophes, becuase it is not a valid JS Object key. You need to write e.g. ng-style="{'font-size': '12px'}".

    Secondly, ng-style attribute is being evaluated as JS, so you can't use the double curly braces syntax, because it is not a valid JS. Just write like you would inside JS: ng-style="{'font-size': writing_size + 'px'}".

    Your working example:

      <!DOCTYPE html>
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    
    
    <title>AngularJS Whiteboard</title>
    </head>
    
    <body>
    
    <div ng-app="">
    
    
    
    <textarea name="message" rows="10" cols="30" ng-model="writing">
    </textarea>
    <span>    Marker color: <input type = "text" size = "7" ng-model="marker_color"></span>
    <span>    Writing size: <input type = "text" size = "7" ng-model="writing_size"></span>
    
    <br>
    <br>
    
    <div id = "whiteboard" ng-bind="writing" ng-style="{ color : marker_color, 'font-size': writing_size + 'px' }">   
    </div>
    
    <div id = "test">
    {{ writing_size + "px"}}
    </div>
    
    </div>
    
    </body>
    </html>