我想订阅一个 ngChange 事件,但从代码而不是标记。也就是说,给定一个 $scope 和一个可通过 ngModel 绑定的表达式,我想订阅绑定到该表达式的任何 ngModel 指令对该表达式所做的任何更改。这可能吗?
就像是:
$scope.field = "hello";
$scope.onButtonClick = function() {
$scope.field = "button clicked!";
}
// this callback is only when the user types in an input bound to field
// not when they click the button with ng-click="onButtonClick()"
$scope.$watchNgChange("field", function() {
console.log("user caused field to change via a binding");
});
// this callback is called for both ngModel binding changes and onButtonClick.
$scope.$watch("field", function() {
console.log("field was changed");
});
我不能只使用 $watch,因为它会捕获所有更改,包括从数据库加载数据、ng-click 回调以及从 $watch 回调为其他表达式发起的更改(在这种情况下,如果有任何循环引用,那么很容易让 $watch 回调进入无限循环并在 10 个摘要循环后出错),谁知道还有什么。