我正在做一个元素,我的要求是动态提供页面内容,其中将包含不同的 div 或表格,我还需要在运行时为这些 div 传递样式,这些样式可以更改很多次。我在元素中使用 AngularJS。我可以找到一些 resource其中适用于 div 的该类的 css 属性之一是使用 ng-model 传递的,但我想传递我的整个 CSS 属性,适用于该类(可能采用 json 的形式)来自 Textarea页面元素。
感谢这方面的任何帮助。非常感谢!
我的部分代码如下:
<div ng-style="sampleStyle" class="col-md-6 ">{{sampleText}}</div>
<textarea ng-model="sampleText" cols="40">
</textarea>
<textarea ng-model="sampleStyle" cols="40">
</textarea>
我要传递的 CSS 格式是:
{
color: xxx; background: xxx; font-size: xx; ...
}
最佳答案
尝试使用 ng-class
代替。
html:
<div ng-class="sampleStyle" class="col-md-6 ">{{sampleText}}</div>
<textarea ng-model="sampleText" cols="40"></textarea>
<textarea ng-model="sampleStyle" cols="40"></textarea>
编辑:
要将样式文字动态绑定(bind)到元素,您不能简单地使用 ng-model,因为 Angular 会将其解释为字符串,而不是对象。您需要先使用 $parse
在作用域上创建一个 js 对象,并从 ng-style 中引用它。
html:
<div ng-class="myStyle" class="col-md-6 ">{{sampleText}}</div>
<textarea ng-model="sampleText" cols="40"></textarea>
<textarea ng-model="sampleStyle" ng-change="styleChangeFn()" cols="40"></textarea>
js:
app.controller('MainCtrl', ["$scope", "$parse", function($scope, $parse) {
$scope.styleChangeFn = function() {
$scope.myStyle = $parse($scope.sampleStyle)($scope);
}
}]);
关于javascript - 如何动态改变网页的内容和样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265407/