我有一个表单,我试图在输入中使用一个函数ng-checked="someFunction()",我不知道这是否可能或我做错了什么.我在我的控制器中有功能,我在视野中调用它.至于功能,我认为它肯定工作,ng-checked正在解雇它但返回true或false不会改变任何东西.那么问题是有没有办法在'ng-checked'中使用函数?
$scope.multiAnswers = function (answers, optionId) {
angular.forEach(answers, function (answer, key) {
if (answer.option_choice_id == optionId) {
return true;
}
});
return false;
};
Run Code Online (Sandbox Code Playgroud)
Kha*_* TO 20
ng-checked确实可以使用功能.这是一个演示:
$scope.getCheckedFalse = function(){
return false;
};
$scope.getCheckedTrue = function(){
return true;
};
Run Code Online (Sandbox Code Playgroud)
HTML:
<input type="checkbox" ng-checked="getCheckedFalse()"/>
<input type="checkbox" ng-checked="getCheckedTrue()"/>
Run Code Online (Sandbox Code Playgroud)
你的问题是你在函数结束时永远不会返回true.return true;在angular.forEach内部没有帮助.
尝试:
$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;
};
Run Code Online (Sandbox Code Playgroud)
看起来我们无法摆脱angular.forEach:Angular JS打破ForEach
要提高性能时,立即突破answer.option_choice_id == optionId是真实的.你可以试试jQuery $ .each或使用vanilar javascript(for loop).