Javascript Angularjs:复选框和 ng-change

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43676631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:05:48  来源:igfitidea点击:

Angularjs: checkbox and ng-change

javascriptangularjscheckboxangularjs-ng-change

提问by mpeg90

I have problems to understand how ng-change works. I have a list of user to invite to join an auction. I want to do this with a checkbox. If the user is checked, his name has to be saved into an array. And later i will invite them(i just know how to do this). But i don't understand how to use the checkbox. I did something like this:

我无法理解 ng-change 的工作原理。我有一个邀请用户参加拍卖的列表。我想用一个复选框来做到这一点。如果用户被选中,他的名字必须保存到一个数组中。稍后我会邀请他们(我只知道如何做到这一点)。但我不明白如何使用复选框。我做了这样的事情:

<ul class="list-group" ng-repeat="user in users">
    <li class="list-group-item" ng-hide="user.name == profile">
        <img ng-src="{{user.img}}" class="image2" >
        <div class="username"> {{user.name}}</div>
        <div class="userrole"> {{user.role}} </div>
        <div class="usercompany">{{user.company}}</div>
        <input type="checkbox"  ng-model="isChecked" ng-change="insertinvited(user.name)">
    </li>
</ul>

And in my controller:

在我的控制器中:

$scope.invited = [];
$scope.insertinvited= function (name) {
    if($scope.isChecked){
        $scope.invited.push(name)
    } else {
        console.log($scope.invited);
    }
};

But this is not working, in the console the array is always empty.

但这不起作用,在控制台中数组始终为空。

回答by Mistalis

The problem in your code is that your checkbox model (isChecked) is used by all the usersyou ngRepeated on:

您的代码中的问题是您的复选框模型 ( isChecked) 被所有usersngRepeated 使用:

<ul class="list-group" ng-repeat="user in users">
    ...
    <input type="checkbox" ng-model="isChecked" ng-change="insertinvited(user.name)">
</ul>

I suggest you to have a checkbox model for eachuser:

我建议您为每个用户设置一个复选框模型:

<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">

Note that in your ng-change, I pass the whole userobject, and not only user.name(because I will also need the user.isCheckedproperty).

请注意,在您的 中ng-change,我不仅传递了整个user对象user.name(因为我还需要该user.isChecked属性)。



Here is the "new" insertinvited()function:

这是“新”insertinvited()功能:

$scope.insertinvited = function(user) {
    if(user.isChecked) {
        $scope.invited.push(user.name);
    } else {
        var toDel = $scope.invited.indexOf(user);
        $scope.invited.splice(toDel);
    }
}

回答by tanmay

What you need here is isCheckedfor all the items in ng-repeatand not just as single variable. So, I changed your checkboxlike:

您在这里需要的是isChecked所有项目,ng-repeat而不仅仅是单个变量。所以,我改变了你的checkbox喜好:

<input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">

Here's working example:

这是工作示例:

angular.module("myApp", [])
  .controller("myCtrl", function($scope) {
    $scope.users = [{
      name: "test1",
      role: "manager",
      company: "google",
      img: ""
    }];

    $scope.invited = [];
    $scope.insertinvited = function(user) {
      if (user.isChecked) {
        $scope.invited.push(user.name)
      } 
      console.log($scope.invited);

    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul class="list-group" ng-repeat="user in users">
    <li class="list-group-item" ng-hide="user.name == profile">
      <img ng-src="{{user.img}}" class="image2">
      <div class="username"> {{user.name}}</div>
      <div class="userrole"> {{user.role}} </div>
      <div class="usercompany">{{user.company}}</div>
      <input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
    </li>
  </ul>
</div>

EDIT: However, doing it this way, you would need to handle removal also. I'd suggest you go with following approach instead.

编辑:但是,这样做,您还需要处理删除。我建议你改用以下方法。

Explanation: On change of any checkbox value, you filter all the users with isCheckedset to true.

说明:在更改任何复选框值时,您将使用isCheckedset过滤所有用户true

angular.module("myApp", [])
  .controller("myCtrl", function($scope) {
    $scope.users = [{
      name: "test1",
      role: "manager",
      company: "google",
      img: ""
    }];

    $scope.invited = [];
    $scope.insertinvited = function() {
      $scope.invited = $scope.users.filter(obj => obj.isChecked)
      $scope.invited = $scope.invited.map(obj => obj.name)
      console.log($scope.invited);

    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <ul class="list-group" ng-repeat="user in users">
    <li class="list-group-item" ng-hide="user.name == profile">
      <img ng-src="{{user.img}}" class="image2">
      <div class="username"> {{user.name}}</div>
      <div class="userrole"> {{user.role}} </div>
      <div class="usercompany">{{user.company}}</div>
      <input type="checkbox" ng-model="user.isChecked" ng-change="insertinvited(user)">
    </li>
  </ul>
</div>

回答by Volodymyr Kozlov

Use it

用它

<input type="checkbox" id="{{'j' + $index}}" name="{{'j' + $index}}" ng-model="tasks.Checked" ng-change="checkinTask(tasks)"

This Part from controller.

这部分来自控制器。

$scope.checkinTask = function (task) {

                        if (task.Checked === true) {
                            task.Lineclass = "checkedTask";
                            $scope.disabled = false;
                            trash.removeClass("disabled");
                        } else {
                            task.Lineclass = "";
                        }
                        var checkedExist = false;
                        tasks.forEach(function (v) {
                            if (v.Checked) {
                                checkedExist = true;
                            }
                        });
                        if (!checkedExist) {
                            $scope.disabled = true;
                            trash.addClass("disabled");
                        }
                    };