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.

1
  • 1
    If you are using controller as, aren't you missing the name of your controller before the function toggleSelection(...)? Commented Sep 28, 2015 at 9:47

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

Why though? Shouldn't the 'this' syntax work exactly as scope?
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 stackoverflow.com/a/14168699
-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"

3 Comments

Sorry, but that was not it, that was actually a mistake on my copy-pasting.
@Tiago Please provide code on JS Fiddle or Plunker.
You say he wrote a line that he did not.. you done messed it up;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.