Angular Modal UI变量未被监听:变量变更时监听函数不触发排查
Angular Modal中$watch监听未触发的问题排查
嘿,我看了你的代码,发现问题其实出在**$watch回调函数里的变量引用错误**,另外还有个小细节需要注意,咱们一步步来:
1. 核心错误:回调参数引用错误
你在$watch的回调里写了alert('value='+$scope.newValue),但这里的newValue是回调函数的局部参数,并不是$scope上的属性!所以你拿到的$scope.newValue是undefined,导致alert弹出来的内容不对,让你误以为$watch没触发。
修复这个很简单,直接用回调里的newValue参数就行:
$scope.$watch('x', function (newValue, oldValue) { if (typeof newValue === 'undefined') return; alert('value=' + newValue); // 这里改成newValue,不是$scope.newValue });
2. 额外验证:确认scope绑定是否正确
你在打开模态框时指定了scope: $scope,这意味着模态框里的ng-model="x"直接绑定到了父控制器的$scope.x,所以输入框的变化确实会同步到父scope,$watch应该能监听到。如果修复了上面的问题后还是没触发,可以检查以下两点:
- 确保ui-bootstrap的版本和Angular版本兼容(比如Angular 1.x对应ui-bootstrap 0.x/1.x版本)
- 有没有其他代码不小心覆盖了$scope.x的值,或者意外使用了隔离scope(不过你这里明确用了父scope,所以这个可能性很低)
修复后的完整代码
JavaScript部分
var app = angular.module('app', ['ui.bootstrap']); app.controller('ctl', function ($scope,$uibModal) { $scope.x = 'a'; $scope.open = function(){ $scope.modalInstance = $uibModal.open({ templateUrl: 'myModalContent.html', scope: $scope }); }; $scope.close = function(){ $scope.modalInstance.close(); }; $scope.$watch('x', function (newValue, oldValue) { if (typeof newValue === 'undefined') return; alert('value=' + newValue); // 修正变量引用 }); });
HTML部分
<button ng-click="open()">Open</button> <script type="text/ng-template" id="myModalContent.html"> <div class="modal-header"> <h4 class="modal-title">The Title</h4> value <input type="text" ng-model="x" /> <button ng-click="close()">Close</button> </div> </script>
这样修改后,当你在模态框的输入框里修改内容时,$watch就会正常触发,弹出对应的新值啦。
内容的提问来源于stack exchange,提问作者ps0604
相关产品推荐
相关产品推荐

