AngularJS ng-repeat设置字体颜色

时间:2014-11-24 10:56:57

标签: angularjs

我有以下代码

<div ng-repeat="cat in filteredTodos">
   <input class='inputIsActive' type="checkbox" ng-checked="{{cat.isActive}}"/>
   <span>{{cat.isActive}}</span>
</div>

isActive可以有truefalse值。如何根据<span>值设置isActive字体颜色?

3 个答案:

答案 0 :(得分:1)

您可以使用ng-class

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.filteredTodos = [{
    isActive: true
  }, {
    isActive: false
  }];
}
&#13;
.active {
  color: green;
}
.inactive {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="cat in filteredTodos">
    <input class='inputIsActive' type="checkbox" ng-checked="{{cat.isActive}}" />
    <span ng-class="{ active: cat.isActive, inactive: !cat.isActive }">{{cat.isActive}}</span>
  </div>
</div>
&#13;
&#13;
&#13;

或使用ng-style

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.filteredTodos = [{
    isActive: true
  }, {
    isActive: false
  }];
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="cat in filteredTodos">
    <input class='inputIsActive' type="checkbox" ng-checked="{{cat.isActive}}" />
    <span ng-style="{color: cat.isActive ? 'green' : 'red'}">{{cat.isActive}}</span>
  </div>
</div>
&#13;
&#13;
&#13;


修改

使用ng-model代替ng-checked

&#13;
&#13;
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.filteredTodos = [{
    isActive: true
  }, {
    isActive: false
  }];
}
&#13;
.active {
  color: green;
}
.inactive {
  color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="cat in filteredTodos">
    <input class='inputIsActive' type="checkbox" ng-model="cat.isActive" />
    <span ng-class="{ active: cat.isActive, inactive: !cat.isActive }">{{cat.isActive}}</span>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<span style="color: {{cat.isActive? 'green' : 'red'}}">blue</span> eyes.</p>

这可能有用

答案 2 :(得分:0)

您可以使用ng-classng-style

<span ng-class="{'active' : cat.isActive , 'not-active' : !cat.isActive}">{{cat.isActive}}</span>

 .active { 
     color:green;
 }

.not-active { 
     color:red;
 }

<span ng-style="{color: (cat.isActive ? 'green' : 'red' )}">{{cat.isActive}}</span>

这是工作plunker