簡體   English   中英

每當輸入更改時,AngularJS ng-change

[英]AngularJS ng-change whenever input changes

我有一個類型為email的輸入:

<input type="email" ng-model="user.email" name="email" required>

現在, 無論何時更改輸入,我都需要執行一些代碼。 如果輸入的字符串是有效的電子郵件地址,添加ng-change="emailInputChanged()"僅會執行我的方法,但是即使輸入未通過驗證,我也需要在每次擊鍵時執行回調。 (當觀看模型$scope.$watch('user.email', emailInputChanged)

有什么角度的方法嗎?

由於您已將類型指定為電子郵件,因此只有在有效時才調用ng-change ,因此請刪除type屬性

請改用ng-keyup 即使基本事件(本機事件或jQuery事件)也是如此,因為表單僅在場模糊時才會正常反應。

要捕獲其他粘貼事件,請使用ng-paste指令(請參閱https://code.angularjs.org/1.4.6/docs/api/ng/directive/ngPaste

我建議使用onInput事件: http : //www.w3schools.com/jsref/event_oninput.asp創建一個自定義指令,並在文本字段元素上偵聽“ input”事件。

指令實現的示例:

function OnInput() {
  return {
    restrict: 'A',
    template: '',
    scope: {
      whenInputChanged: '&'
    },
    link: function($scope, $element, $attrs) {
      $element.on('input', $scope.whenInputChanged);
    }
  };
}

angular.module('App')
  .directive('onInput', OnInput);

要在模板中應用事件監聽器:

<input type="email" on-input when-input-changed="change()" name="email" required/>

請享用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM