【问题标题】:calling a function in ng-checked在 ng-checked 中调用函数
【发布时间】:2023-03-25 17:12:01
【问题描述】:

我正在尝试对复选框中的 ng-checked 执行功能。基本上我想让复选框选中取决于某些条件。我遵循 AngularJs ng-checked using a function..它工作正常。但我发现该函数调用了6次!!!

html代码:

          <label>
          <input type="checkbox" 
               ng-checked="getCheckedValue()">
        </label>

角度js函数:

            $scope.getCheckedValue = function(){
             alert("checking ...");
             var isChecked=false;
             if(some condition){
              isChecked=true;
               return;
             }
             return isChecked;
            }

我的 js 收到了 6 次警报!!请帮帮我

【问题讨论】:

  • 一个小提琴会很好。 :)
  • angular 中的摘要循环可以运行多次...通常设置范围变量比在标记中使用函数更好。为什么不能在函数中设置变量并在标记中使用该变量?
  • 请检查您调用函数 getcheckedValue() 的位置。尝试更换内部控制器。
  • 这里的问题是你将一个函数作为 watch 键传递给 angularjs,所以任何时候为所述范围执行摘要循环,该函数都会被调用...jsfiddle.net/arunpjohny/zskxcgsq/1
  • 不用手表也能做到 - jsfiddle.net/arunpjohny/zskxcgsq/4

标签: javascript angularjs


【解决方案1】:

从 cmets 来看,我认为你可以在加载医生列表后不使用手表来更新检查状态

<table>
    <tr ng-repeat="doctor in doctorList">
        <td data-ng-bind="doctor.firstName"></td>
        <td ng-repeat="timeSlot in timeSlots">
            <input type="checkbox" ng-checked="doctor[timeSlot]" />
        </td>
    </tr>
</table>

然后一旦加载了医生列表

    angular.forEach($scope.doctorList, function (doctor) {
            angular.forEach($scope.timeSlots, function (slot) {
            doctor[slot] = $scope.isChecked(doctor, slot)
            });
    });

演示:Fiddle

【讨论】:

    猜你喜欢
    • 2014-03-09
    • 2018-07-11
    • 2015-08-11
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多