Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs ng-checked using a function

Tags:

angularjs

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;
    };
like image 388
sarunast Avatar asked Feb 11 '14 12:02

sarunast


People also ask

How do I check if a checkbox is checked in AngularJS?

The ng-checked Directive in AngularJS is used to read the checked or unchecked state of the checkbox or radio button to true or false. If the expression inside the ng-checked attribute returns true then the checkbox/radio button will be checked otherwise it will be unchecked.

How do you use NG value?

The AngularJS ng-value directive is used to set the value attribute of an input element, or a select element. It is mainly used on <radio> and <option> elements to set the bound values when these elements are selected. It is supported by <input> and <select> elements.


1 Answers

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).

like image 74
Khanh TO Avatar answered Oct 07 '22 18:10

Khanh TO