2014-09-19 79 views
3

我需要一種方法來在當前頁面上存在未保存的更改時中斷導航到新頁面的用戶。我實現了這裏的解決方案的修改版本:

http://weblogs.asp.net/dwahlin/cancelling-route-navigation-in-angularjs-controllers

不過,我在瀏覽器中看到的是,只要一個鏈接,用戶點擊,視圖的變化和新的控制器負荷完全同時顯示模態對話框。當用戶點擊「取消」並觸發event.preventDefault時,用戶只需結束新視圖。這很奇怪,因爲我讀過的所有內容都表明這是可接受的方法,而且似乎沒有人會遇到這個問題。然而,我不能在我的生活中看到我的代碼出了什麼問題。

下面是用於處理位置變化的主要應用功能(ModalService只是包裝的角度引導$模式服務):

onRouteChangeOff = $rootScope.$on('$locationChangeStart', routeChange); 

    function routeChange(event, newUrl, oldUrl) { 
     //Navigate to newUrl if the form isn't dirty 
     if (!$rootScope.unsavedChanges) return; 

     var modalOptions = { 
      closeButtonText: 'Cancel', 
      actionButtonText: 'Ignore Changes', 
      headerText: 'Unsaved Changes', 
      bodyText: 'You have unsaved changes. Leave the page?' 
     }; 

     ModalService.showModal({}, modalOptions).result.then(function() { 
       $rootScope.unsavedChanges = false; 
       $location.path(newUrl); //Go to page they're interested in 
      } 
     , function() { 
      event.preventDefault(); 
     });   
     return; 
    } 

任何想法?

+0

在打開模式之前防止默認 – vil 2014-09-19 04:35:05

+0

這沒有幫助我害怕。新的控制器/視圖在模式打開之前已經加載,並且不管我是否調用event.preventDefault。 – 2014-09-19 07:18:17

+0

只有在更改視圖之前,纔會在更改開始時調用此函數。只需嘗試在路由更改函數中只有event.preventDafault,以檢查它是否僅限制url中的更改。然後,您可以檢查功能中是否有其他錯誤。 – Kop4lyf 2014-09-19 08:07:25

回答

4

如果有其他人有這個問題,修復後來變得非常簡單。我將代碼移到了stateChangeStart事件中。代碼看起來像這樣:

onRouteChangeOff = $rootScope.$on('$stateChangeStart', routeChange); 

    function routeChange(event, newState) { 
     //Navigate to newUrl if the form isn't dirty 
     if (!$rootScope.unsavedChanges) return; 
     event.preventDefault(); 
     var modalOptions = { 
      closeButtonText: 'Cancel', 
      actionButtonText: 'Ignore Changes', 
      headerText: 'Unsaved Changes', 
      bodyText: 'You have unsaved changes. Leave the page?' 
     }; 

     ModalService.showModal({}, modalOptions).result.then(function() { 
      $rootScope.unsavedChanges = false; 
      $state.go(newState); //Go to page they're interested in 
     }); 
    } 
+0

感謝分享的人,作品完美。但是我在想什麼關於州的參數。 – 2017-05-15 13:30:37