【问题标题】:How to detect the input fields are changed in Angularjs如何检测Angularjs中的输入字段发生变化
【发布时间】:2015-04-29 22:49:19
【问题描述】:

现在我有一个页面供用户输入一些数据,这不是表单。 如:

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

有一个退出按钮让用户回到他们原来的地方。问题是如果用户不更改或修改任何输入。(假设他们只是意外到达这里)当他们点击退出按钮时,他们可以直接返回,但如果他们做了一些更改,如果他们想返回,我需要显示一个弹出窗口来确认他们想要离开而不保存数据。我怎样才能抓住它?

我尝试使用 $watch,但似乎对我不起作用:

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;
              }     
              }); 
             }
            })
        })

【问题讨论】:

  • 目前还不清楚您要在这里做什么。您列出了一对绑定到 ExpReport 属性的输入框,以及一个角度代码的 sn-p,这表明范围内可能有多个 ExpReport,对于每个您似乎都在观看一个名为 @ 的属性987654326@ 这甚至不是输入框之一。

标签: angularjs


【解决方案1】:

为“$locationChangeStart”(如果使用 ui-router,则为“$stateChangeStart”)事件添加一个事件监听器。当它触发时,您可以提示用户确保他们想要丢失所有更改。

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

【讨论】:

  • 虽然这可能有效,但它并没有真正回答所提出的问题,因为问题中没有迹象表明发布者甚至使用了 $stateChangeStart 是成员的 ui-router 插件的。
  • 我认为这正是作者需要做的问题:保留旧数据的副本,然后按照@HankScorpio 的建议在路线更改时检查新的表单数据。
  • 感谢您提供信息,在 userHasUnsavedChanges 中,如何检查每个文件是否已更改?
  • 采纳弗拉基米尔的建议。克隆不会被修改的数据。在该函数中比较两者。但实际上,将输入放入表单中会容易得多。然后你可以检查myFormName.$pristine。如果有任何修改都是错误的。
猜你喜欢
  • 2013-07-29
  • 1970-01-01
  • 2017-08-24
  • 2020-07-24
  • 2017-01-08
  • 2012-09-29
  • 2011-09-25
  • 2014-07-11
相关资源
最近更新 更多