angular1.x 簡單的全選功能
阿新 • • 發佈:2019-01-07
var m1 = angular.module('testModule', ['ngRoute']);
m1.controller("testController", ["$scope", "$location", function ($scope, $location) {
//設定基本資訊
$scope.content = [
{
id: 10,
baseInfo: {
name: 'hanker'
},
orgCompanyName : 'ali'
},
{
id: 11,
baseInfo: {
name: 'hanker'
},
orgCompanyName : 'ali'
},
{
id: 12,
baseInfo: {
name: '222'
},
orgCompanyName : 'ali'
},
{
id: 13 ,
baseInfo: {
name: 'hanker111'
},
orgCompanyName : 'baidu'
},
{
id: 14,
baseInfo: {
name: 'eeee'
},
orgCompanyName : 'tenxun'
}
];
//建立變數用來儲存選中結果
$scope.selected = [];
//動作 和 id號 如果是add則把id號放入 selected陣列中
var updateSelected = function (action, id) {
if (action == 'add' && $scope.selected.indexOf(id) == -1) $scope.selected.push(id);
if (action == 'remove' && $scope.selected.indexOf(id) != -1) $scope.selected.splice($scope.selected.indexOf(id), 1);
};
//更新某一列資料的選擇
$scope.updateSelection = function ($event, id) {
console.log( id );
var checkbox = $event.target;
console.log( checkbox );
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
//全選操作
$scope.selectAll = function ($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
// 遍歷這個 content 把所有的元素從selected中新增或刪除
for (var i = 0; i < $scope.content.length; i++) {
var contact = $scope.content[i];
updateSelected(action, contact.id);
}
};
$scope.isSelected = function (id) {
return $scope.selected.indexOf(id) >= 0;
};
//如果資料長度 == 全選的
$scope.isSelectedAll = function () {
return $scope.selected.length === $scope.content.length;
};
}]);