Rendy Rendy - 1 year ago 408
AngularJS Question

Changing ng-class not updating style?

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?

Answer Source

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