angularjs 如何處理checkbox

直接上程序代碼:

index.html

<div>
    <div ng-repeat="color in colors">
        <input type="checkbox" ng-checked="isChecked(color.id)" 
            ng-click="updateSelection($event,color.id)" />{{color.name}}
    </div>
</div>
<div>
    Selected : {{selected}}
</div>

controller.js

psmsApp.controller("vipApplyEditCtrl", function($scope) {
	$scope.colors = [
	    {id : 1, name : 'black'},
	    {id : 2, name : 'red'},
	    {id : 3, name : 'blue'},
	    {id : 4, name : 'yellow'},
	    {id : 5, name : 'green'},
	    {id : 6, name : 'white'}
	] ;
	
	$scope.selected = [] ;
	
	$scope.isChecked = function(id){
		return $scope.selected.indexOf(id) >= 0 ;
	} ;
	
	$scope.updateSelection = function($event,id){
		var checkbox = $event.target ;
		var checked = checkbox.checked ;
		if(checked){
			$scope.selected.push(id) ;
		}else{
			var idx = $scope.selected.indexOf(id) ;
			$scope.selected.splice(idx,1) ;
		}
	} ;
});

效果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章