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

标签 javascript angularjs

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

相关文章:

javascript - 使用 Promise 的 MongoDB 查询性能

javascript - 是否可以从 JavaScript 动态创建 Firebase 实时数据库并获取其 API key ?

javascript - 当用户刷新页面时,如何进行 angularjs $http POST 调用?

javascript - 根据javascript/angularjs中的括号解析AND和OR条件语句?

AngularJS/ Material : why the expression is not evaluated?

javascript - 在 browserify 中使用 Angular 模板缓存

c# - 这可以改进吗?清除危险的 html 标签

javascript - Ember.js REST 适配器使用 JSON 根(使用 ember-data)

javascript - angular.js 没有将 css 应用于附加的 html 元素?

javascript - Angularjs - NgView 不工作