AngularJS:尝试通过组合变量和 "px" 来创建样式值

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

我制作了一个程序,允许用户在 "white board" 上书写文本并实时更改颜色。我现在正试图让用户也能够更改字体大小。我如何将 "writing_size" 变量与字符 "px" 组合起来形成 "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>

第一个问题:font-sizemust not be used without apostrophes,因为它不是有效的 JS 对象键。你需要写例如ng-style="{'font-size': '12px'}".

其次,ng-style 属性正在被评估为 JS,因此您不能使用双花括号语法,因为它不是有效的 JS。就像在 JS 中那样写:ng-style="{'font-size': writing_size + 'px'}".

您的工作示例:

  <!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>