【问题标题】:Run ng-change functions on load for pre-checked checkboxes在加载时为预先选中的复选框运行 ng-change 函数
【发布时间】:2016-08-03 12:25:41
【问题描述】:

我在 ng-change 中有一个函数,每次选中复选框时都会执行(手动)。

现在我想在加载时预先检查复选框,并且 ng-change 中的函数也可以执行(加载时)。

我可以采取哪些方法来实现这一目标?

【问题讨论】:

  • ng-init?你有没有尝试过?
  • ng-init 是我尝试用来初始化函数的第一个指令;但是,没有返回预期的结果。想知道除了 ng-init 是否还有其他方法。
  • 您没有使用控制器或指令吗?我不明白为什么不能直接从控制器初始化/指令链接上的 JS 调用您在 ng-change 中调用的函数。 ng-change="update()" -> scope.update(); // on controller

标签: javascript jquery angularjs checkbox


【解决方案1】:

你不需要这样做,你的模型会自动这样做,比如说

$scope.customer = 客户;

<input type='checkbox' ng-model='customer.active' /> Is Active

它会自动处理

【讨论】:

  • ... 除了 OP,实际上可能需要调用 ngChange 中的方法,而您的解决方案并未涵盖。
【解决方案2】:

如果你想要一个在加载和 onChange 事件期间触发的函数,你可以使用指令 ng-init

创建连接到您的作用域的 onLoad 和 onChange 函数:

$scope.onLoad = function(params) {
  // do some init functionality and call onChange functionality
  onChange();
}

$scope.onChange = function(value) {
  // do function when a combobox is chaned
}

在 HTML 模板中你必须绑定这些方法

<div ng-init="onLoad()">
  <input type='checkbox' ng-model='someModel' ng-change="('1')"/> Is one
  <input type='checkbox' ng-model='someModel' ng-change="('2')"/> Is two
  <input type='checkbox' ng-model='someModel' ng-change="('3')"/> Is three
</div>

【讨论】:

    【解决方案3】:

    ng-change 不会执行,除非用户更改了输入,如角度文档here 中所述。问题是您可以手动触发 ng-change,但通常不建议这样做,它被认为是 dirty way and terrible practice。添加观察者并检测对模型所做的任何更改会更合适。

    $scope.$watch("myModel", function(newValue, oldValue){
        // do something
    });
    

    【讨论】:

    • 有手动触发ng-change的例子吗?
    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2020-10-21
    • 2018-02-19
    • 1970-01-01
    • 2015-12-16
    相关资源
    最近更新 更多