ngChange-like functionality for the entire form

后端 未结 4 2081
余生分开走
余生分开走 2020-12-05 04:21

I would like to do an equivalent of ng-change for the entire form whenever there is a change in one of its input fields.

I know that since AngularJS 1.3

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 04:57

    one "hacky" way to do this is by setting a watcher to the form dirty, valid depending on your requirements you can do something like

       $scope.$watch('form.$dirty',function(v){
             if(!v){return}
             form.$setPristine()
             /*do something here*/
        })
    

    this will execute everytime the form gets modified, if you only want to execute your code on valid modified form you can do

           if(!v || form.$invalid){return}
    

    and if you only want to execute your code when the form steps to $valid state just need to set up your watcher for 'form.$valid'

    if you don't like to pollute your scope with watchers, you can always create a directive around the form that exposes a on-change api event and internally takes care of the watcher

提交回复
热议问题