Reputation: 5698
I have following code:
Pug:
div(ng-class="('{{selectedMessageType}}' == 'incoming')?'messageTypeSelected':'messageTypeNotSelected'")
CSS:
.messageTypeSelected{
background-color: #E8A83C;
color: #ffffff;
}
.messageTypeNotSelected{
background-color: #E4E4E4;
}
JS:
$scope.selectedMessageType = 'incoming';
$scope.changeMessageType = function(){
($scope.selectedMessageType == 'incoming')?$scope.selectedMessageType = 'outgoing':$scope.selectedMessageType = 'incoming';
};
My {{selectedMessageType}}
is replaced correctly with the logic. I have also checked on it using Inspector on browser. However, the styling is not applied, when value is changed.
What could be wrong in my code?
Upvotes: 1
Views: 1142
Reputation: 24894
You don't need the {{}}
in ngClass
directive.
Change your code to:
<div ng-class="selectedMessageType == 'incoming' ? 'messageTypeSelected' : 'messageTypeNotSelected'"></div>
A working code
:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope'];
function MainCtrl($scope) {
$scope.selectedMessageType = 'incoming';
$scope.changeMessageType = function() {
$scope.selectedMessageType = $scope.selectedMessageType == 'incoming' ? 'outgoing' : 'incoming';
}
}
})();
.messageTypeSelected {
background-color: #E8A83C;
color: #ffffff;
}
.messageTypeNotSelected {
background-color: #E4E4E4;
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-class="selectedMessageType == 'incoming' ? 'messageTypeSelected' : 'messageTypeNotSelected'">
<span ng-bind="selectedMessageType"></span>
</div>
<hr>
<button type="button" value="change" ng-click="changeMessageType()">Change class</button>
</body>
</html>
I'd recommend you to check this tutorial
Upvotes: 1
Reputation: 43619
ngClass does not work the way you wrote it. It takes in the format of:
ng-class="{'css-class': trueOrFalseExpression}"
the trueOrFalseExpression
could be selectedMessageType == 'incoming'
Upvotes: 1