如果在 jQuery 委托事件处理程序中更改了 AngularJS 模型,它不会立即更新
AngularJS model won't update immediately if it is changed in a jQuery delegated event handler
我在这里为我的问题设置了一个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();
});
相关文章:
- 如何将ng选项的索引作为angularJs中的值传递给模型
- Angularjs无法将单选按钮与嵌套范围内的模型绑定
- AngularJS-使模型变量可用于jQuery
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- 自定义指令中的AngularJS ng模型
- 模型更改时的AngularJS动画
- AngularJS在更改模型时引发更改
- Angularjs:如何让ui选择只有一种方式的模型竞标
- AngularJS模型在手动更改选项后不会更新
- AngularJS+IE 11+聚合物=ng模型未更新
- 如何在angularjs中点击按钮重置模型
- AngularJS ng下拉树结构的模型定义
- 延迟 AngularJS 路由更改,直到加载模型以防止闪烁
- 需要使用触摸屏从 AngularJS 指令中更新模型
- AngularJs 切换模板 URL 并访问模型数据
- 如何将子值绑定到模型 angularjs
- 父/子模型AngularJS上的默认ngOptions
- 如何向控制器发送数据,比如Model有列表模型AngularJs
- 更新模型angularJS
- 为这个JSON输入数组定义ng模型——AngularJS