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

时间:2017-03-06 04:38:00

标签: angularjs angularjs-ng-click ng-class ng-style

.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元素通过使用条件为“已选择”className时,如何在ng-style中添加'myStyle'。如果ng-class条件为真,如何动态应用内联ng-style?在下面我可以在调试器中看到内联添加了classNames。现在我的条件为true,我可以看到类名为“selected”(class =“test ng-scope selected”),我想要的是内联ng-style =“myStyle”,当它为true时添加。

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

2 个答案:

答案 0 :(得分:2)

尝试这样。

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

<强> 演示

&#13;
&#13;
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;
}
})
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

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

执行此操作

风格

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