选中复选框后如何更改订单清单的字体颜色?

时间:2019-01-02 09:27:18

标签: html angularjs

我正在开发带有选中和取消选中复选框的列表,并且列表位于数组中,并且我无法使用angularjs和html更改列表中的字体颜色

这类似于待办事项列表选项页面,汽车列表将具有“是”和“否”复选框,但是当我尝试检查并取消选中它对列表中的第一个对象起作用时,请帮助我在列表中执行相同的操作< / p>

<div ng-app="myApp" ng-controller="orderCtrl">
<ul style="list-style-type:none">
<li id="list" ng-repeat="x in cars | orderBy">
   <input type="checkbox" id="selected" ng-model="cars[x]" onchange="changeColor()"/> 
   <input type="checkbox" id="nonSelected" onchange="changeColor()"/>{{x}}</li>
</ul>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
    $scope.cars = ["Porsche", "Bentley", "Audi", "Ferrari", "BMW", "Ford"];
});
function changeColor()
{
    if(document.getElementById("nonSelected").checked==true){
        document.getElementById("list").style.color="red";
        document.getElementById("selected").disabled = true;
        return;
    }
    else if(document.getElementById("selected").checked==true){
        document.getElementById("list").style.color="green";
        document.getElementById("nonSelected").disabled = true;
        return;
    } else {
        document.getElementById("list").style.color="black";
        document.getElementById("selected").disabled = false;
        document.getElementById("nonSelected").disabled = false;
        return;
    }

}
</script>

当我选中复选框时,结果必须是列表,列表字体必须更改颜色,并且在数组列表中应该禁用另一个复选框

1 个答案:

答案 0 :(得分:0)

您没有以正确的方式使用AngularJS。您面临的问题是由于每辆车的每个输入的ID相同。以下是您遇到的问题的有效代码。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = ["Porsche", "Bentley", "Audi", "Ferrari", "BMW", "Ford"];
$scope.cars.sort();
$scope.car_obj = [];
for (var i=0; i<$scope.cars.length; i++){
    $scope.car_obj.push({name: $scope.cars[i], selected: false, nonSelected: false}) 
}
$scope.getCheckedCount = function(type){
  return $scope.car_obj.filter(function(car){return car[type]}).length;
}
  
});
.text-red {
  color: red;
}

.text-green {
  color: green;
}

.text-black {
  color: black;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
  <div>selected: {{getCheckedCount('selected')}}</div>
  <div>nonSelected: {{getCheckedCount('nonSelected')}}</div>

<ul style="list-style-type:none">
<li id="list" ng-repeat="x in car_obj">
   <input type="checkbox" ng-model="x.selected" ng-disabled="x.nonSelected"/> 
  <input type="checkbox" ng-model="x.nonSelected" ng-disabled="x.selected"/><span ng-class="{'text-red': x.nonSelected, 'text-green': x.selected}">{{x.name}}</span></li>
</ul>

</div>

</body>
</html>