[英]Using ng-change in AngularJS with “Controller As” syntax
[英]AngularJS - ng-change fired with the controller initialization
我的模板中有以下內容:
<input name="searchText" placeholder="Search" data-type="search"
ng-model="searchText"
ng-change="searchRecords()"
ng-keyup="onKeyUp()">
當我轉到該模板時,將調用searchRecords()
函數(觸發ng-change)。 我希望僅當我開始鍵入時才調用searchRecords()
(更改searchText
將觸發ng-change
)。 現在,它通過控制器初始化被觸發。
我試圖設置searchText
到null
, ''
的控制器,但它是一樣的。
這是設計使然,還是我缺少了某些東西?
編輯:
我意識到這段代碼會觸發我的searchRecords()
:
$scope.$watchGroup(['daysBefore', 'daysAhead'], function (newValues, oldValues, scope) { ... }
編輯:
我刪除了ng-change
並添加了以下內容:
$scope.$watch('searchText', function (newValue, oldValue) {
$scope.searchRecords();
});
在不更改$scope.searchText
此代碼在控制器初始化時執行。
您可以使用ng-init來設置標志,例如:“ ng-init ='initializing = true'”,然后在ng-change函數中檢查
您無需使用ng-change即可為該輸入的ng-model創建觀察者。
$scope.$watch(function() { return $scope.searchText; }, function(n, o) { if(n != o){ $scope.searchRecords(); } }, true);
<input ng-model="searchText">
干杯
如果您有ng-model,那么發生ng-change事件是正常的。 您應該改為對$ scope.searchText var進行$ watch。
我在Google網上論壇找到了關於此的主題-https://groups.google.com/forum/#! topic/ angular/ uXldMqsQvRw
手表在注冊時自動觸發(並通過$ evalAsync異步觸發),這將初始化手表並讓您的代碼知道初始值。
如果不希望這樣做,則可以將此檢查放入您的保存方法中:
函數save(newVal,oldVal){如果(newVal === oldVal)返回; //在這里做事}
是的,我想擺脫這種代碼,但顯然我不能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.