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 回のダイジェスト サイクル後にエラーが発生するのは簡単すぎます)。