1. 程式人生 > >AngularJS 之ng-class 按條件設定class的幾種方式

AngularJS 之ng-class 按條件設定class的幾種方式

第一種:在dom中將class的值用變數替代,然後在controller函式中設定變數的值。如下所示: 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        .p_class{
            background-color: #00b3ee;
        }
    </style>
</head>
<body ng-controller="myController">

<p ng-class="p_class">測試ng-css</p>


<script>

    var app=angular.module("myApp",[]);

    app.controller("myController", function ($scope) {
        $scope.p_class="p_class"
    })

</script>

</body>
</html>

這種方式偏離了檢視和模型分開的原則,不建議使用

第二種:用方括號和變數形式,將變數至於dom中,在controller函式中控制 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        .active{
            background-color: #00b3ee;
        }
    </style>
</head>
<body ng-controller="myController">

<p ng-class="{true:'active',false:'inactive'}[active]">測試ng-css</p>


<script>

    var app=angular.module("myApp",[]);

    app.controller("myController", function ($scope) {
        $scope.active=true
    })

</script>

</body>
</html>

在controller中控制active變數的真和假,如果為真就取active類,如果為假就取inactive類。這種方式適合一個dom設定單個類的情況 

第三種:通過物件設定,這種方式適合給一個dom設定多種類的情況,形式如下: 

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
    <style>
        .active{
            background-color: #00b3ee;
        }
    </style>
</head>
<body ng-controller="myController">

<p ng-class="{'tipIp': nti.type==='ip', 'tipCc': nti.type==='cc', 'tipUrl': nti.type==='url'}">測試ng-css</p>


<script>

    var app=angular.module("myApp",[]);

    app.controller("myController", function ($scope) {

    })

</script>

</body>
</html>