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

Gay*_*yan 4 angularjs angular-ui angular-ui-router

我试图在我的应用程序上停止导航,如果任何表单进行了更改并尝试导航而不保存更改.

我想显示一个对话框,显示是保存导航或放弃还是取消导航操作.

我正在使用角度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'
        })
});
Run Code Online (Sandbox Code Playgroud)

我计划实现类似于使用angularjs服务单例的实现

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


});
Run Code Online (Sandbox Code Playgroud)

在控制器级别,我可以像这样写一个提交点击

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

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

谢谢

Rad*_*ler 9

答案是:可以将这种支票转移到服务/工厂 - 以便进一步重复使用.此外,这里有一些例子,至少要展示如何 - 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 };
})
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

和控制器:

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

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

  CheckStateChangeService.checkFormOnStateChange($scope);

})
Run Code Online (Sandbox Code Playgroud)

有一个例子