更改ng-class不更新样式?

时间:2016-07-27 02:45:36

标签: css angularjs

我有以下代码:

帕格:

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';
};

我的{{selectedMessageType}}被逻辑正确替换。我还在浏览器上使用Inspector检查了它。但是,当值更改时,不会应用样式。

我的代码可能有什么问题?

2 个答案:

答案 0 :(得分:1)

您不需要{{}}指令中的ngClass

将您的代码更改为:

<div ng-class="selectedMessageType == 'incoming' ? 'messageTypeSelected' : 'messageTypeNotSelected'"></div>

正在工作 code

&#13;
&#13;
(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';
    }
  }
})();
&#13;
.messageTypeSelected {
  background-color: #E8A83C;
  color: #ffffff;
}

.messageTypeNotSelected {
  background-color: #E4E4E4;
}
&#13;
<!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>
&#13;
&#13;
&#13;

我建议您查看tutorial

答案 1 :(得分:1)

ngClass不像您编写的那样工作。它采用以下格式:

ng-class="{'css-class': trueOrFalseExpression}"

trueOrFalseExpression可能是selectedMessageType == 'incoming'