13

I have a form and I am trying to use a function in input ng-checked="someFunction()" and I don't know if this is possible or I am doing something wrong. I have function in my controller and I am calling it in view. As far as the function I think it's definitely working and the ng-checked is firing it but returning true or false doesn't change anything. So the question would be is there a way to use function in 'ng-checked' ?

$scope.multiAnswers = function (answers, optionId) {
  angular.forEach(answers, function (answer, key) {
    if (answer.option_choice_id == optionId) {
      return true;
    }
  });
  return false;
};
1
  • 1
    Afaik ng-checked is used only with on/off value with a model. So you could exploit the model instead. Commented Feb 11, 2014 at 12:22

2 Answers 2

23

ng-checked does work with functions. Here is a demo:

$scope.getCheckedFalse = function(){
    return false;
};

$scope.getCheckedTrue = function(){
    return true;
};

Html:

<input type="checkbox" ng-checked="getCheckedFalse()"/>
<input type="checkbox" ng-checked="getCheckedTrue()"/>

DEMO

Your problem is that you never return true at the end of the function. return true; inside angular.forEach does not help.

Try:

$scope.multiAnswers = function (answers, optionId) {
     var returnValue = false;
     angular.forEach(answers, function (answer, key) {
         if (answer.option_choice_id == optionId) {
              returnValue = true;
              return;
         }
     });

     return returnValue;
};

It looks like that we cannot break from angular.forEach: Angular JS break ForEach

To improve performance to break immediately when answer.option_choice_id == optionId is true. You could try jQuery $.each or using vanilar javascript (for loop).

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

1 Comment

that's awesome. .
3

What you need to do is use a state variable as the ng-checked expression, eg: ng-checked="someValue". Then it is up to you elsewhere in your code to update that $scope value. The problem is that by using a function, it is unaware when in fact it should update its value.

4 Comments

It's in the scope. Sorry I pass 'this' object later to the scope. It wasn't obvious from the code.
Thanks for explaining. I was having similar ideas, the problem is that I can't use the variable because the forms are dynamic. Is there some other way ? Using a filter maybe ?
You will need to elaborate. Are you able to create a fiddle?
It's quite hard to make a fiddle. Basically I generate different types forms from database using angularjs. And I want to show which options of check-box were selected in the past by the user.

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.