如果 ng-class 为真,我如何动态应用 ng-style?

How can I apply ng-style dynamically if ng-class is true?

.test{color:red;background:blue;}
.test.selected {
position:relative;  left: 100px; padding:10px; background:green;
}

<div ng-style="myStyle" ng-class="{select: x.selected}" ng-click="select(x)" ng-repeat="x in myData" class="test"></div>


$scope.select = function (text) {   
    text.selected = true;
};

$scope.myStyle = {
    'color':'white',
    'font-weight':'bold'
}

当 div 元素通过使用条件 true 具有 className "selected" 时,我如何在 ng-style 中添加 'myStyle' 。如果 ng-class 条件为真,如何动态应用内联 ng-style?在下面,我可以在调试器中看到内联添加了 classNames。现在我的条件为真,我可以看到它的 classname "selected"(class="test ng-scope selected"),我想要的只是一个内联的 ng-style="myStyle" 为真时添加。

<div ng-class="{select: x.selected}" ng-click="select(x)" class="test ng-scope selected" ng-repeat="x in myData"> 

这样试试。

<div ng-style="x.selected && {'color':'white','font-weight':'bold'}"  
    ng-click="select(x)" ng-repeat="x in myData" ></div>

演示

var app = angular.module('anApp', ['angular.filter']);
app.controller('aCtrl', function($scope) {
  $scope.data = [
  {
    "id": 100,
    "value": "2452"
  },
  {
    "id": 100,
    "value": "2458"
  },
  {
    "id": 1,
    "value": "2457"
  },
  {
    "id": 1,
    "value": "2459"
  },
  {
    "id": 4,
    "value": "2460"
  },
  {
    "id": 5,
    "value": "3458"
  }
];

$scope.select = function(x){
  x.selected = !x.selected;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
<div ng-style="x.selected && {'color':'red','font-weight':'bold'}"  
    ng-click="select(x)" ng-repeat="x in data" >
      {{x.value}}
    </div>

</div>

不要对所选项目使用 ng-style,您可以使用 ng-class(Recommended)

风格

.selected {
 'color':'white',
 'font-weight':'bold'
}

HTML

<div ng-class="{'selected': x.selected}" ng-click="select(x)" ng-repeat="x in myData" ></div>

控制器

$scope.select = function(x){
  x.selected = !x.selected;
}