请帮我处理以下代码。我创建了这个,以便任何人都可以进行更改并给我一个解决方案。
HTML
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="continent in destinations">
<input type="checkbox" ng-model="continent.selected" ng-change="parentChange($index)"> {{continent.name}} ({{continent.countries_selected}}
/ {{continent.countries.length}}) - {{continent.all_selected}}
<ul>
<li ng-repeat="country in continent.countries">
<input type="checkbox" ng-model="country.selected"> {{country.name}} </li>
</ul>
</li>
</ul>
<p>You have selected: {{total_selected}} Countries in Total</p>
</body>
</html>
控制器
app.controller('MainCtrl', function($scope) {
$scope.total_selected = 0;
$scope.$watch('destinations', function(destinations){
var total_selected = 0;
angular.forEach(destinations, function(continent){
continent.countries_selected = 0;
angular.forEach(continent.countries, function(country){
total_selected += country.selected ? 1 : 0
continent.countries_selected += country.selected ? 1 : 0
if (continent.countries_selected == continent.countries.length) {
continent.selected = true;
} else {
continent.selected = false;
}
});
});
$scope.select_all = function(continent){
continent.selected = true;
}
$scope.total_selected = total_selected;
}, true);
$scope.select = function(continent){
console.log(continent)
continent.selected = true;
}
$scope.parentChange = function(index) {
angular.forEach( $scope.destinations[index].countries, function(country) {
country.selected = $scope.destinations[index].selected;
});
};
$scope.destinations = [
{
"name": "India",
"countries": [
{
"name": "Mumbai"
},
{
"name": "Delhi"
},
{
"name": "Calicut"
}
]
},
{
"name": "America - US",
"countries": [
{
"name": "New York"
},
{
"name": "Canada"
},
{
"name": "Miami"
},
{
"name": "Hackensack"
}
]
}
];
});
我想做的是:
对于Ex:如果我选择子节点(德里),则应自动检查父节点(印度)。
换句话说,检查的任何子节点都应该立即检查父节点,反之亦然
谢谢, Kimz。
答案 0 :(得分:0)
这是一个非常简单的变化,现在你正在观看变化的集合并在其中进行此更改
if (continent.countries_selected == continent.countries.length) {
continent.selected = true;
} else {
continent.selected = false;
}
然而你真正想要的是,如果为该大陆选择了至少一个国家/地区,那么只需将其更改为
if (continent.countries_selected > 0) {
continent.selected = true;
} else {
continent.selected = false;
}