不允许如果形式的任何变化使用$脏和$原始导航 [英] not allow to navigate if any changes on form using $dirty and $pristine

查看:114
本文介绍了不允许如果形式的任何变化使用$脏和$原始导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止我的应用程序导航,如果任何形式的更改,并尝试不保存更改导航。

I'm trying to stop navigation on my application if any form made changes and try to navigate without saving changes.

我要显示一个对话框,显示是否保存浏览或放弃或取消导航操作。

i want to show a dialog to show whether to save navigate or discard or cancel navigation action.

我使用的角度 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服务单

i was planning to have implementation something like using angularjs service singleton

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


});

和控制器层面,我可以写一个点击提交这样

and on controller level i can write a submit click like this

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

我不知道有没有简单的方法已经存在与否

i'm not sure is there easy way exist already or not

感谢您

推荐答案

答案是:这是确定移动那样的支票到服务/工厂 - 一些进一步的重用。另外,这里是一些例子至少说明如何 - plunker

The answer is: It is ok to move that kind of check into service/factory - for some further reuse. Also, here is some example at least to show how to - 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);

})

有一个例如

这篇关于不允许如果形式的任何变化使用$脏和$原始导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆