Issue
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;
};
Solution
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()"/>
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).
Answered By - Khanh TO
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.