我有一个复选框列表。每当我单击一个复选框时,我想根据它是否被选中或未选中来调用一个函数。这是使用 ng-change
同时,我还有 ng-checked
来帮助我使用按钮取消选中复选框。
具体实现如下:
<md-checkbox md-no-ink="true" ng-checked="selected.indexOf(brand) > -1" ng-change="value?add(brand):remove(brand)" ng-model="value" ng-repeat="brand in brands">
{{brand}}
</md-checkbox>
<md-button ng-click="fun('Spice')">Uncheck</md-button>
Controller 代码如下:
$scope.brands = ['Apple','Samsung','Motorolla','Nokia','Micromax','Spice'];
$scope.value = false;
$scope.selected = [];
$scope.fun = function(x){
console.log("Unchecking "+x);
}
$scope.add = function(x){
$scope.selected.push(x);
}
$scope.remove = function(x){
var index = $scope.selected.indexOf(x);
$scope.selected.splice(index,1);
}
Stackovrflow 上有一个类似的问题,但它存在有关复选框上缺少 ng-model 的问题。我在这里包含了 ng-model
。
为什么这不起作用?我做错了什么吗?
最佳答案
Note that this directive should not be used together with ngModel, as this can lead to unexpected behavior.
您应该决定是使用 ng-model
还是 ng-checked
。不幸的是,目前无法在 md-checkbox
指令 ( see this bug ) 上使用 ng-checked
。所以你必须使用ng-model
。以下代码应该对您有帮助。
HTML
<md-checkbox md-no-ink="true" ng-model="selected[$index]" ng-repeat="brand in brands track by $index">
{{brand}}
</md-checkbox>
Is Samsung selected: {{isSelected('Samsung')}}
JS
$scope.brands = ['Apple','Samsung','Motorolla','Nokia','Micromax','Spice'];
$scope.selected = [];
$scope.isSelected = function(brand) {
var brandIndex = $scope.brands.indexOf(brand);
return $scope.selected[brandIndex]
};
请注意,每个复选框都需要自己的模型。在您使用 $scope.value
作为所有复选框的单个模型之前 - 在这种情况下,它们会同时被选中/取消选中。
我相信上面的代码就是您正在寻找的代码。如果我没有捕获重点,请随时发表评论。
关于javascript - 为什么 `ng-checked` 不能与 `ng-change` 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129892/