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;
};
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With