AngularJs ng-checked using a function

后端 未结 2 1049
面向向阳花
面向向阳花 2020-12-15 08:35

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 ha

相关标签:
2条回答
  • 2020-12-15 08:59

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

    0 讨论(0)
  • 2020-12-15 09:04

    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.

    0 讨论(0)
提交回复
热议问题