Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ng-change not fired from checkbox inside label

I have some HTML like this:

<input ng-controller="cboxCtrl" type="checkbox" 
       ng-model="hideCompleted" ng-change="hideChanged()"/>

and a controller like this:

angular.module('simple-todos').controller('cboxCtrl', ['$scope',  
function ($scope) {
    console.log("starting");

    $scope.hideChanged = function () {
        console.log("in hideChanged() ");
    };
}]); // end controller

It works fine and I see the message on the console when I click the checkbox. However, if I add a label around the checkbox:

<label>
    <input ng-controller="cboxCtrl" type="checkbox" 
           ng-model="hideCompleted" ng-change="hideChanged()"/>
    Some text to explain the checkbox
</label>

The ng-change function does not run when I click the checkbox. I expect it has something to do with scoping but I cannot figure out what. If I replace labels with divs (which of course does not give a "nice" laýout), the ng-change function is again executed as expected.

like image 969
Per Beliing Avatar asked Nov 09 '22 22:11

Per Beliing


1 Answers

I just created a jsfiddle with your code and it works for me.

https://jsfiddle.net/jfplataroti/hphb8c4v/5/

angular.module('simple-todos', []).controller('cboxCtrl', ['$scope', cboxCtrl]);


function cboxCtrl($scope) {
  console.log("starting");

  $scope.hideChanged = function() {
    console.log("in hideChanged() ");
  };
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="simple-todos">
  <label>
    <input ng-controller="cboxCtrl" type="checkbox" ng-model="hideCompleted" ng-change="hideChanged()" />some text for the label
  </label>
</div>

would you mind sharing your complete code?

like image 110
jfplataroti Avatar answered Nov 14 '22 21:11

jfplataroti