AngularJS点击输入框内清除按钮,绑定JSON对象未同步清空求助
问题原因分析
- 直接通过jQuery修改input的
val("")属于原生DOM操作,Angular的双向绑定机制无法感知到这个变化,因此绑定的dl.ModelA/ModelB不会同步更新。 ClearText函数中,ngModelTo是值传递(字符串属于基本类型,参数传递时会拷贝值),赋值ngModelTo = ""只会修改局部变量,不会影响原对象dl.ModelA/ModelB。
解决方案
方案1:修复jQuery代码,触发Angular的ngModel更新
修改SetClearButtonInTextBox中清除按钮的点击逻辑,使用Angular官方API更新模型,而非直接修改DOM值:
function SetClearButtonInTextBox(Callback) { if (!window.document.documentMode) { $("input").each(function () { var im = $(this); if (!$(this).parent().hasClass("text-input-wrapper") && !$(this).hasClass("btn")) { $(this).wrap("<div class='text-input-wrapper'></div>"); $(this).after("<button class=\"Covered\" type=\"button\">×</button>"); } $(this).closest("div.text-input-wrapper").find("button").mousedown(function () { // 获取输入框对应的Angular ngModel控制器 var ngModelCtrl = angular.element(im[0]).controller('ngModel'); if (ngModelCtrl) { // 用Angular API更新视图值,同步到模型 ngModelCtrl.$setViewValue(''); ngModelCtrl.$render(); // 手动触发change事件,执行ng-change绑定的逻辑 im[0].dispatchEvent(new Event('change')); } }); }); } }
同时修改ClearText函数和输入框的ng-change绑定,解决值传递问题:
修改输入框定义:
<input name="ModelA" ng-model="dl.ModelA" ng-change="ClearText(this, 'ModelA');"/> <input name="ModelB" ng-model="dl.ModelB" ng-change="ClearText(this, 'ModelB');"/>
修改ClearText函数:
$scope.ClearText=function(target, propName){ if (target.target.value == "") { // 通过对象属性名直接修改原对象,确保双向绑定同步 $scope.dl[propName] = ""; } }
方案2:改用Angular自定义指令(推荐)
避免jQuery和Angular的DOM操作冲突,用Angular指令实现清除按钮,更符合框架规范:
定义自定义指令:
angular.module('yourAppModule').directive('clearableInput', function() { return { restrict: 'A', template: ` <div class="text-input-wrapper"> <input ng-model="innerModel" ng-change="triggerOnChange()"/> <button class="Covered" type="button" ng-click="clearInput()">×</button> </div> `, scope: { ngModel: '=', ngChange: '&' }, link: function(scope) { // 同步外部ngModel到指令内部 scope.$watch('ngModel', function(newVal) { scope.innerModel = newVal; }); // 同步内部值到外部ngModel scope.$watch('innerModel', function(newVal) { scope.ngModel = newVal; }); // 清除输入框逻辑 scope.clearInput = function() { scope.innerModel = ''; scope.triggerOnChange(); }; // 触发外部的ng-change事件 scope.triggerOnChange = function() { scope.ngChange(); }; } }; });
使用指令:
<input clearable-input name="ModelA" ng-model="dl.ModelA" ng-change="ClearText(this, dl.ModelA);"/> <input clearable-input name="ModelB" ng-model="dl.ModelB" ng-change="ClearText(this, dl.ModelB);"/>
所有操作都在Angular生命周期内,双向绑定会自动同步,无需额外处理DOM。
内容的提问来源于stack exchange,提问作者Gary Lu
相关产品推荐
相关产品推荐

