2017-01-11 148 views
0

我正在使用AngularJs,其中我有一個複選框集合,並且已將其中一個項目設置爲選定項目。該index.cshtml具有以下代碼:將複選框設置爲默認按鈕在AngularJS中單擊

<div ng-controller="testController" ng-init="init()"> 
    <form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate=""> 
     <div class="container" ng-show="createMenu"> 
     <div class="row"> 
      <div class="col-lg-2 col-md-2 col-sm-2 "> 
      <label>Delivery Method</label> 
      </div> 
      <div class="col-lg-2 col-md-2 col-sm-2" ng-repeat="method in deliveryMethods"> 
      <input type="checkbox" id="{{method.id}}" value="{{method.value}}" name="deliveryMethod[]" ng-model="method.selected" ng-click="toggleSelection(method.value)" ng-required="!someSelected"> {{method.value}} 

      </div> 

     </div> 
     <span style="color:red" ng-show="submitted == true && !someSelected">Delivery is required</span> 

     <input type="button" id="btnReset" value="Cancel" ng-click="reset()" /> 
     </div> 
    </form> 
    </div> 

複選框數據在controller.js填充如下:

$scope.deliveryMethods = [{ 
    "id": 1, 
    "value": "test-up", 
    selected: true, 
}, { 
    "id": 2, 
    "value": "test two", 
    selected: false 
}, { 
    "id": 3, 
    "value": "test three", 
    selected: false 
}]; 

這裏,「測試行動」是默認選擇。如果我選擇「測試二」選項,然後單擊取消,我想將複選框「測試」設置爲選中狀態。我曾嘗試下面的代碼,但不工作:

$scope.clear = function() { 
    $scope.deliverySelection = ["test-up"]; 
    $scope.submitted = false; 
    $scope.clearAll(); 
} 

$scope.reset = function() { 
    $scope.clear(); 
} 
$scope.toggleSelection = function toggleSelection(deliveryMethods) { 
    var idx = $scope.deliverySelection.indexOf(deliveryMethods); 
    // is currently selected 
    if (idx > -1) { 
    $scope.deliverySelection.splice(idx, 1); 
    } else { 
    $scope.deliverySelection.push(deliveryMethods); 
    } 
    someSelected(); 
}; 
$scope.someSelected = true; 

function someSelected() { 
    $scope.someSelected = false; 
    for (var i = 0; i < $scope.deliveryMethods.length; i++) { 
    if ($scope.deliveryMethods[i].selected == true) { 
     $scope.someSelected = true; 
     return false; 
    } 
    } 
} 


$scope.clearAll = function() { 
    angular.forEach($scope.deliveryMethods, function(checkbox_id) { 
    if (checkbox_id.id != 1) 
     checkbox_id.selected = false; 
    }); 

} 

如何設置複選框「測試機」作爲託運,點擊取消按鈕時? 感謝

回答

1

嘗試,而不是你清除所有功能這

$scope.clearAll = function() { 
    angular.forEach($scope.deliveryMethods, function(checkbox_id) { 
    checkbox_id.selected = false; 
    if (checkbox_id.id == 1) { 
     checkbox_id.selected = true; 
    } 
    }); 
} 
相關問題