鍍金池/ 問答/HTML5/ 求一個(gè)angular方法,判斷復(fù)選框是否全選和復(fù)選框是否多選?

求一個(gè)angular方法,判斷復(fù)選框是否全選和復(fù)選框是否多選?

求一個(gè)angular方法,判斷復(fù)選框是否全選和復(fù)選框是否多選?
需求是,

當(dāng)我點(diǎn)擊選中指定項(xiàng)后,angular變成全選
當(dāng)我再次點(diǎn)擊選中指定向后,angular變成單選
如果是單選,我想要知道單選項(xiàng)
如果是多選,我需要判斷是否是選擇了全選功能,

clipboard.png

就是類似的這個(gè)功能。求大佬指點(diǎn),謝謝了?。。。。?/p>

回答
編輯回答
胭脂淚

clipboard.png

2017年7月18日 16:03
編輯回答
裸橙

angular 2.x

.template

<table>
<tbody>
<ng-container *ngFor="let group of groups">
<tr style="background-color: gray;">
 <td><input type="checkbox" [(ngModel)]="group.checked" (change)="turnAll(group)">全選</td>
 <td>{{group.name}}</td>
</tr>
<tr *ngFor="let item of group.items">
 <td><input type="checkbox" (change)="turnItem(group)" [(ngModel)]="item.checked"></td>
 <td>{{item.price}}</td>
 <td>{{item.prop1}}</td>
 <td>{{item.propN}}</td>
</tr>
</ng-container>
</tbody>
</table>

.ts

groups: Array<any> = [{ name: 'group1', items:[...] }, { name: 'group2', items:[...] }];
lock=false;

turnItem(group) {
    if(lock) return;
    lock=true;
    group.checked=group.items.every(item => item.checked);
    lock=false;
}

turnAll(group){ 
    if(lock) return;
    lock=true;
    group.items.forEach(i=>i.checked=group.checked); 
    lock=false;
}

angular 1.x

.html

<table>
<tbody>
<ng-container ng-repeat="group in groups">
<tr style="background-color: gray;">
 <td><input type="checkbox" ng-model="group.checked" ng-change="turnAll(group)">全選</td>
 <td>{{group.name}}</td>
</tr>
<tr ng-repeat"item in group.items">
 <td><input type="checkbox" ng-change="turnItem(group)" ng-model="item.checked"></td>
 <td>{{item.price}}</td>
 <td>{{item.prop1}}</td>
 <td>{{item.propN}}</td>
</tr>
</ng-container>
</tbody>
</table>

.js

app.controller('myCtrl', function($scope) {
    var lock=false;
    
    $scope.groups = [{ name: 'group1', items:[...] }, { name: 'group2', items:[...] }];
    
    $scope.turnItem(group) {
    if(lock) return;
    lock=true;
    group.checked=group.items.every(item => item.checked);
    lock=false;
}

$scope.turnAll(group){ 
    if(lock) return;
    lock=true;
    group.items.forEach(i=>i.checked=group.checked); 
    lock=false;
}

});
2017年7月4日 13:36
編輯回答
脾氣硬

你要的功能不就是根據(jù)頁面的選中情況把數(shù)據(jù)發(fā)送回服務(wù)端么?你之前的描述和你的需求完全是兩回事。
angular做這個(gè)功能就非常容易,angular的核心是雙向數(shù)據(jù)綁定,嵌套循環(huán)搞定這個(gè)很容易。第一個(gè)大循環(huán)把外層的列表顯示出來,然后再把選中項(xiàng)的數(shù)據(jù)循環(huán)出來,放到彈窗里就行了。不需要關(guān)心你之前寫的那些判斷,angular自己能搞定。你唯一要做的東西,就是在用戶全選的時(shí)候,需要循環(huán)子選項(xiàng),把他們都設(shè)置成1.之后post的時(shí)候,直接把數(shù)據(jù)發(fā)回去就可以了。因?yàn)槭请p向綁定,選中和取消都會(huì)在數(shù)據(jù)中直接引起數(shù)據(jù)變化,不需要手動(dòng)改變數(shù)據(jù)。

2017年12月30日 06:11
編輯回答
落殤

同意樓上的,遍歷,簡單粗暴。

不想遍歷就每次單擊的時(shí)候計(jì)數(shù)唄,不過我還是覺得遍歷好,比較也沒DOM啥的,遍歷挺快的

2018年3月15日 14:36
編輯回答
硬扛

循環(huán)input判斷,最簡單粗暴

2017年10月11日 18:35