linyuanxie
linyuanxie

Reputation: 787

How to detect the input fields are changed in Angularjs

Now I have a page for user to enter some data, which is not form. Such as:

<input type='text' ng-model='ExpReport.ReportName' /> <input type='text' ng-model='ExpReport.startdate' />

there is a exit button to let user go back to where they came from. The problem is if user don't change or modify any input.( assume they just accidently get here) when they hit the exit button, they can directlly go back, but if they made some change, if they want to go back, I need to show a popup to confirm that they want to leave without saving data. How can I catch it?

I try to use $watch, but seems like doesn't work for me:

angular.forEach($scope.ExpReport,function(value,key){
            $scope.$watch('value',function(oldvalue,newvalue){
                   var currenturl = $location.path();
          if(currenturl.indexOf('editreport')>-1){
           $scope.$on('$locationChangeStart', function( event,next,current) {      
              event.preventDefault();
              $scope.existconfirm = true; 
                if(next.indexOf('editreport')>-1) {
                $scope.existconfirm = false;
              }     
              }); 
             }
            })
        })

Upvotes: 0

Views: 2429

Answers (1)

HankScorpio
HankScorpio

Reputation: 3651

Add an event listener to the '$locationChangeStart' (or '$stateChangeStart' if using ui-router) event. When it fires ou can prompt the user to make sure they want to lose all their changes.

$scope.$on('$locationChangeStart', function (event) {
    if(userHasUnsavedChanges() && !confirm('Are you sure you want to abandon your changes?')){
        event.preventDefault();
    }
});

Upvotes: 1

Related Questions