AngularJS ng-class
Getting classy, makin' bootstrap sexy
by Steven Senkus
HTML
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<div ng-app="classApp" ng-controller="bootstrapController">
<input ng-model="message" />
<button class="btn btn-default" ng-class="{ 'btn-danger': isOne(),
'btn-warning': isTwo(), 'btn-info': isThree(), 'btn-success': isFourOrMore() }">Button State</button>
</div>
CSS
div {
padding: 20px;
}
.btn {
transition: all 0.3s linear;
}
JavaScript
var app = angular.module('classApp', []).
controller('bootstrapController', ['$scope', function ($scope) {
$scope.isOne = function () {
if (typeof $scope.message !== 'undefined' ) {
return $scope.message.length == 1;
} else {
return false;
}
}
$scope.isTwo = function () {
if (typeof $scope.message !== 'undefined' ) {
return $scope.message.length == 2;
} else {
return false;
}
}
$scope.isThree = function () {
if (typeof $scope.message !== 'undefined' ) {
return $scope.message.length == 3;
} else {
return false;
}
}
$scope.isFourOrMore = function () {
if (typeof $scope.message !== 'undefined' ) {
return $scope.message.length >= 4;
} else {
return false;
}
}
}]);