1

In my Angular app, I have a form with checkbox inputs:

<div ng-repeat="partner in type.partners">
    <label class="checkbox-inline">
        <input type="checkbox" value="partner"
        ng-checked="report.participatingPartners[$parent.$index].indexOf(partner) !== -1" 
        ng-click="toggleSelection($parent.$index, $index);">
        <p><span></span>{{partner.name}}<p>
    </label>
</div>

And in my controller, just to test this setup:

var vm = this;
vm.toggleSelection = toggleSelection;

...

function toggleSelection(typeId, partnerId) {
    console.log("toggleSelection called");
    console.log(typeId, partnerId);
}

This function never gets called when I click the checkbox or its label. Why is that?

I know it's not the controllerAs syntax because other functions are working fine.

Tiago
  • 4,233
  • 13
  • 46
  • 70
  • 1
    If you are using controller as, aren't you missing the name of your controller before the function `toggleSelection(...)`? – Maxime Morin Sep 28 '15 at 09:47

3 Answers3

2

The attribute you probably want to use is ng-change. The angular input directive does not have ng-clicked or ng-checked.

See docs.

1

By putting the function that you are trying to reference in the ng-click onto $scope rather than onto this the click event should bind as desired.

On the controller...

$scope.toggleSelection = toggleSelection;

 function toggleSelection(typeId, partnerId) {
    ...
}

On your html...

<input type="checkbox" value="partner"
    ng-click="toggleSelection($parent.$index, $index);">

Here is a simple Fiddle of it working.

hally9k
  • 2,423
  • 2
  • 25
  • 47
  • Why though? Shouldn't the 'this' syntax work exactly as scope? – Tiago Sep 28 '15 at 14:05
  • Because `this` refers to the controller object not the `$scope` object. These are two different things. `$scope` is the API that the controller exposes to the view. The view cannot access functions on the controller object. To clarify read this excellent answer http://stackoverflow.com/a/14168699 – hally9k Sep 29 '15 at 09:55
-1

You have written below code:

ng-checked="vm.toggleSelection($parent.$index, $index);"

But it should be:

ng-checked="toggleSelection($parent.$index, $index);"

Just remove "vm"

HaRdik Kaji
  • 390
  • 1
  • 11