0

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>
fracz
  • 20,536
  • 18
  • 103
  • 149
DennisM
  • 359
  • 1
  • 3
  • 13

1 Answers1

1

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>
fracz
  • 20,536
  • 18
  • 103
  • 149
  • Thanks! Why do I need apostrophes for the key 'font-size' but not 'color'? – DennisM Oct 26 '18 at 05:45
  • 1
    Because `someObject.font-size` in JS would understood as *subtract `size` from `someObject.font` property*. I.e., it would be read as `someObject.font - size`. The same goes for declaration: `var a = {font-size: 12}` is not valid, but `var a = {'font-size': 12}` is correct. See https://stackoverflow.com/a/4348487/878514 – fracz Oct 26 '18 at 05:53