gpt4 book ai didi

javascript - 为什么 `ng-checked` 不能与 `ng-change` 一起使用?

转载 作者:行者123 更新时间:2023-11-29 17:58:23 25 4
gpt4 key购买 nike

我有一个复选框列表。每当我点击一个复选框时,我想根据它是被选中还是未被选中来调用一个函数。这是使用 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

为什么这不起作用?我做错了什么吗?

最佳答案

official documentation指出

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com