我试图在我的应用程序上停止导航,如果任何表单进行了更改并尝试导航而不保存更改.
我正在使用角度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){ });
在控制器级别,我可以像这样写一个提交点击
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 }; })
并有这样的观点:
<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('MyCtrl',function($scope,CheckStateChangeService) { $scope.person = { Name: "name",Age: 18 }; CheckStateChangeService.checkFormOnStateChange($scope); })
有一个example