AngularJS使用ng-class、ng-style实现动态css样式

菜鸟小窝 2022-08-06 09:20:05 阅读数:885

使用AngularJsclassngng-class

一、style样式

1、ng-style 使用

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<h1 ng-style="myStyle">动态样式</h1>
<script> var app = angular.module("myApp", []); app.controller("myCtrl", function($scope) {
 $scope.myStyle = {
 "color" : "white", "background-color" : "coral", "font-size" : "60px", "padding" : "50px" } }); </script>
</body>
</html>

2、双向绑定样式值(不推荐)

这种方式在 IE 下是不兼容的。可以用 ng-styleng-class来代替。

style="background:{
{(releaseFlag == 1)?'#28a745':'#ddd'}};color:{
{(releaseFlag == 1)?'white':'black'}};"
style="background:{
{(releaseFlag == 2)?'#28a745':'#ddd'}};color:{
{(releaseFlag == 2)?'white':'black'}};"

二、Class样式

1、条件判断

根据flag的值来切换不同的class

ng-class={
red:flag==1,blue:flag!=1}

注意:以上写法在实验的过程中可用,但是我移到项目中就不可以使用了很奇怪,修改如下即可使用(在class名称上加单引号)

ng-class="{'red':flag==1,'blue':flag!=1}"
//或者这样
ng-class={
'red':flag==1,'blue':flag!=1}

报错信息:

angular.min.js:81 Error: [$parse:syntax] http://errors.angularjs.org/undefined/$parse/syntax?p0=-&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=5&p3=%7Bbtn-primary-current%3Aname%3D%3D'123'%7D&p4=-primary-current%3Aname%3D%3D'123'%7D
at https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:6:453
at Ua.throwError (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:150:211)
at Ua.consume (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:151:183)
at Ua.object (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:158:342)
at Ua.primary (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:149:358)
at Ua.unary (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:156:73)
at Ua.multiplicative (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:155:310)
at Ua.additive (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:155:170)
at Ua.relational (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:155:34)
at Ua.equality (https://cdn.xxx.cn/js/angular/1.2.0/angular.min.js:154:397) <input type="text" ng-model="name" class="btn-primary ng-pristine ng-valid" ng-class="{btn-primary-current:name=='123'}">

2、通过值选择

<div ng-class="{true: 'btn-primary', false: 'btn-primary-current'}[flag]">123456</div>
function bu($scope) {
$scope.flag= true;
}

3、双向绑定 class 的值(不推荐)

这种方式在 IE 下是可能也不兼容的。

function bb($scope){
$scope.ss="className";
}
<div class="{
{ss}}"></div>
版权声明:本文为[菜鸟小窝]所创,转载请带上原文链接,感谢。 https://blog.csdn.net/qq_25775675/article/details/126175662