AngularJs ng-checked using a function
Asked Answered
A

2

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;
};
Atp answered 11/2, 2014 at 12:12 Comment(1)
Afaik ng-checked is used only with on/off value with a model. So you could exploit the model instead.Alvinia
T
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).

Tabithatablature answered 11/2, 2014 at 13:6 Comment(1)
that's awesome. .Solanaceous
D
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.

Dufrene answered 11/2, 2014 at 12:15 Comment(4)
It's in the scope. Sorry I pass 'this' object later to the scope. It wasn't obvious from the code.Atp
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 ?Atp
You will need to elaborate. Are you able to create a fiddle?Dufrene
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.Atp

© 2022 - 2024 — McMap. All rights reserved.