bug ng-change with checkbox cheked

1

The bug is as follows, I have 2 checkboxes , the first one is automatically dialed, the second checkbox has the tag ng-change that calls a function in controller , the problem is, when I turn on the second checkbox first, ng-change works and makes call correct of the function, if I trigger the first checkbox automatically marking the second, when I unmark the second, it no longer makes the function call, it buga 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><linkrel="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>
    
asked by anonymous 24.10.2017 / 20:36

1 answer

1

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

I do not know what it is like for you to use two variables with different names, but I've made a solution based on the code given in the question.

See:

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><linkrel="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 ng-change in the first checkbox to change the value of the ck2 variable when it is changed.

See the documentation for $ scope. $ watch

    
25.10.2017 / 14:46