gpt4 book ai didi

angularjs - 如果使用 $dirty 和 $pristine 对表单进行任何更改,则不允许进行导航

转载 作者:行者123 更新时间:2023-12-02 22:26:09 25 4
gpt4 key购买 nike

如果任何表单发生更改,我会尝试停止应用程序上的导航,并尝试在不保存更改的情况下进行导航。

我想显示一个对话框来显示是否保存导航或放弃或取消导航操作。

我正在使用 Angular ui.routing

app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/dashboard');

$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: '/application/private/views/dashboard.html'
})
.state('websites', {
url: '/websites',
templateUrl: '/application/private/views/websites.html'
})
});

我计划进行类似使用 AngularJS 服务单例的实现

app.service('dirtyCheckService', function ($rootScope, dialogService){


});

在 Controller 级别我可以编写这样的提交点击

app.controller('formSubmitCtrl', function ($scope, dirtyCheckService){
dirtyCheckService.checkForm($scope).then(function(){
//allow navigation
},function(){
//not allowed}
});

我不确定是否已经存在简单的方法

谢谢

最佳答案

答案是:可以将这种检查移至服务/工厂 - 以便进一步重用。另外,这里有一些示例至少展示了如何 - plunker

工厂:

.factory('CheckStateChangeService', function($rootScope){

var addCheck = function($scope){

var removeListener = $rootScope.$on('$stateChangeStart'
, function (event, toState, toParams, fromState, fromParams) {

if($scope.form.$pristine)
{
return;
}

var shouldContinue = confirm("The form has changed" +
", do you want to continue without saving");
if(shouldContinue)
{
return;
}
event.preventDefault();
});

$scope.$on("$destroy", removeListener);
};

return { checkFormOnStateChange : addCheck };
})

并且有一个像这样的 View :

<div>
<form name="form">

<dl>
<dt>Name</dt>
<dd><input type="text" ng-model="person.Name" />
<dt>Age</dt>
<dd><input type="number" ng-model="person.Age" />
</dl>

</form>
</div>

Controller :

.controller('MyCtrl', function($scope, CheckStateChangeService) {

$scope.person = { Name: "name", Age: 18 };

CheckStateChangeService.checkFormOnStateChange($scope);

})

有一个 example

关于angularjs - 如果使用 $dirty 和 $pristine 对表单进行任何更改,则不允许进行导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459287/

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