为什么“ng checked”不适用于“ng change”

Why is `ng-checked` not working with `ng-change`?

本文关键字:ng change 适用于 checked 为什么 不适用      更新时间:2023-09-26

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

控制器代码如下:

    $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模型的问题。我在这里包含了ng-model

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

官方文件指出

请注意,此指令不应与ngModel一起使用,因为这可能会导致意外行为。

您应该决定是使用ng-model还是ng-checked。不幸的是,目前无法在md-checkbox指令上使用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用作所有复选框的单个模型之前——在这种情况下,它们将同时被选中/取消选中。

我相信上面的代码就是你想要的。如果我没有抓住要点,欢迎发表评论。