1:scope变量绑定(不推荐使用)
function ctr($scope){ $scope.test =“classname”; }
<div class=”{{test}}”></div>
2:字符串数组形式。
function Ctr($scope) { $scope.isActive = true; }
<div ng-class="{true: 'active',false: 'inactive'}[isActive]">
3:对象key/value处理。
function Ctr($scope) { $scope.isSelected=true; $scope.isCar=true; }
<div ng-class={'selected' isSelected,'car':isCar}"></div> <!-- 当 isSelected = true 则增加selected class;否则删除selected class 当isCar=true,则增加car class, 所以你结果可能是4种组合。 -->实例1:
<div class="container" ng-app="myApp" ng-controller="myCtrl"> <p> <button class="btn btn-info" ng-click="infoClick()">info样式</button> <button class="btn btn-danger" ng-click="dangerClick()">danger样式</button> </p> <div class="alert" ng-class="{'alert-info active':isInfo,'alert-danger':isDanger}"> <p>设置alert 的样式</p> </div> </div>
var app = angular.module('myApp',[]); app.controller('myCtrl',function ($scope) { console.info($scope.style); $scope.infoClick = function () { $scope.isInfo = true; $scope.isDanger = false; } $scope.dangerClick = function () { $scope.isInfo = false; $scope.isDanger = true; } });