gpt4 book ai didi

html - 没有使用表单标签时angularjs如何检测$dirty?

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:24 25 4
gpt4 key购买 nike

我正在使用 $window.addEventListener('beforeunload'... 来检测是否对页面进行了更改,并且它基本上按预期工作。我还使用 $transitions.onStart... 来检测当使用后退/前进浏览器按钮时。我不明白这是如何工作的,因为我的 HTML 模板中没有任何表单标签,只是在 div 中输入。

我已经对此进行了研究,但似乎找不到答案,除了没有必要使用表单标签来检查输入的脏度。我只是不确定这在后台实际是如何工作的。

<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">&times;</button>
<h4 class="modal-title pull-left">New Note</h4>
<div class="clearfix"></div>
</div>
<div class="modal-body">
<input type="textfield" ng-model="detailVM.newNoteContent">
<button ng-click="detailVM.addNewNote()">
Save New Note <span class="fa fa-check"></span>
</button>
</div>

这是我的 HTML 代码。

        // For page reloads and attempts to leave the site
$window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
});

// For when a user hits the back button
$transitions.onStart({}, function ($transition)
{
var answer = confirm("Are you sure you want to leave this page? Changes you made may not be saved.")
if (!answer) {
$transition.abort();
return false;
}
return true;
});

这是我在 Controller 中的内容。

当我在输入中输入数据然后尝试重新加载、关闭或单击后退按钮时,这些显示消息“您确定要离开此页面吗?”但是它是如何检测到输入是脏的呢?

最佳答案

ng-model 不需要采用 form 验证器即可工作。

来自 AngularJS 文档:

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

ngModel is responsible for:

  • Binding the view into the model, which other directives such as input, textarea or select require.
  • Providing validation behavior (i.e. required, number, email, url).
  • Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  • Setting related css classes on the element (ng-valid, ng-invalid, ng-dirty, ng-pristine, ng-touched, ng-untouched, ng-empty, ng-not-empty) including animations.
  • Registering the control with its parent form.

AngularJS ng-model Directive API Reference

如果 form 存在,ngModelController 会将其控件注册到表单。这为您提供了一个很好的容器,用于跟踪整组输入/控件的状态。

关于html - 没有使用表单标签时angularjs如何检测$dirty?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54136976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com