如果在 jQuery 委托事件处理程序中更改了 AngularJS 模型,它不会立即更新

AngularJS model won't update immediately if it is changed in a jQuery delegated event handler

本文关键字:模型 AngularJS 更新 jQuery 事件处理 程序 如果      更新时间:2023-09-26

我在这里为我的问题设置了一个jsfiddle。基本上,我试图让用户通过动态构造与此组关联的选项表来生成 HTML 单选组。然后,我将所有这些选项存储在一个名为 $scope.options 的 Angular 模型中,这是一个数组。每次将新行添加到选项表时,都会将一个新的选项对象推送到选项数组中。很简单,真的。

问题是我的$scope.options模型在事件处理程序终止后没有立即更新。相反,它仅在触发另一个事件时更新。要演示,请转到我的小提琴并在表格中添加 2 个选项。您将看到,添加选项 1 后,选项的数量不会更改,但在开始添加选项 2 时会发生变化。

// add option to the table
$("#table-radio-options").on("click", "button.btn-confirm-option", function (event) {
    var $tr = $(this).closest("tr");
    var $optionText = $tr.find(".option-text").first();
    var $optionValue = $tr.find(".option-value").first();
    // add to the list of options in this scope
    $scope.options.push({
        text: $optionText.val(),
        value: $optionValue.val()
    });
    // change the form into table row with data value
    $optionText.replaceWith("<span>{0}</span>".format($optionText.val()));
    $optionValue.replaceWith("<span>{0}</span>".format($optionValue.val()));
    // remove the confirm 
    $(this).remove();
});

};

如果你

正在处理一个非角度方法,你需要在$apply()中进行$scope更改

// add option to the table
$("#table-radio-options").on("click", "button.btn-confirm-option", function (event) {
    var $tr = $(this).closest("tr");
    var $optionText = $tr.find(".option-text").first();
    var $optionValue = $tr.find(".option-value").first();
    //add this
    $scope.$apply(function(){
        // add to the list of options in this scope
        $scope.options.push({
            text: $optionText.val(),
            value: $optionValue.val()
        });
    })
    // change the form into table row with data value
    $optionText.replaceWith("<span>{0}</span>".format($optionText.val()));
    $optionValue.replaceWith("<span>{0}</span>".format($optionValue.val()));
    // remove the confirm 
    $(this).remove();
});