bug ng-change with checkbox cheked

Asked

Viewed 176 times

1

The bug is this, I have 2 checkboxes, by triggering the first the other is automatically marked, the second checkbox owns the tag ng-change calling a function in the controller, the problem is, when I set the second checkbox first, the ng-change works and makes the call correct function, if I trigger the first checkbox automatically marking the second, when you uncheck the second, it no longer calls the function, it calls the first click in the second checkbox,

I was able to reproduce the error

angular.module('ToDo', [])
.controller('ToDoController', function ($scope) {
    $scope.change = function(){
      console.log("changed");
    };
});
<html ng-app='ToDo'>
  <head>
    <title>My Angular To-Do App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  </head>
  <body ng-controller="ToDoController">
    <input type="checkbox" ng-model="ck1" />
    <br/>
    <input type="checkbox" ng-model="ck2" ng-change="change()" ng-checked="ck1"/>
  </body>
</html>

  • There are several ways to solve this problem. Do you really need the first checkbox model to have a different name than the second? What is the need of the change. Wouldn’t it be better to use one $scope.$watch rather than a function that is captured by ng-change?

1 answer

1

I think in your case it would be better to use the $watch than the ng-change to "track" the changes in the variable.

I do not know what is the need for you to use two variables with different names, but I made a solution based on the code offered in the question.

Behold:

angular.module('ToDo', [])
.controller('ToDoController', function ($scope) {
    $scope.$watch('ck2', function(valor){
      if (valor == true) {
          console.log("changed");
      }
    });
});
<html ng-app='ToDo'>
  <head>
    <title>My Angular To-Do App</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  </head>
  <body ng-controller="ToDoController">
    <input type="checkbox" ng-model="ck1" ng-change="ck2=ck1" />
    <br/>
    <input type="checkbox" ng-model="ck2" ng-checked="ck1"/>
  </body>
</html>

I used the ng-change in the first checkbox and, when changed, change the value of the variable ck2.

See the documentation of $Scope. $watch

  • It is possible to use the watch in several inputs, by the CSS class, for example, is that in vdd I will make a query, and for each row returned I will create 2 inputs, using the same idea, each input checked will automatically check the other corresponding

Browser other questions tagged

You are not signed in. Login or sign up in order to post.