AngularJS注册表单提交时显示等待提示的实现求助
Hey there! Since you're new to AngularJS, let's break down how to add that loading indicator step by step—it's simpler than you think 😊
First, we need a way to track when the app is busy processing the registration request. Let's add a boolean variable to your controller that we'll toggle on and off:
// Inside your controller $scope.isLoading = false; $scope.submitRegistration = function(userObj) { // Turn on loading state when the form is submitted $scope.isLoading = true; createUserService.Register(userObj, function(data) { // Turn off loading state once we get a response $scope.isLoading = false; if (data.error) { console.log("Check " + data.error); } else { alertify.alert("Successfully Registered"); $state.reload(); } }); };
Now, we'll add a visual prompt in your form that only shows when isLoading is true. We'll also disable the submit button to prevent duplicate clicks while waiting:
<!-- Your registration form --> <form ng-submit="submitRegistration(userObj)"> <!-- Your form fields go here (name, email, etc.) --> <!-- Loading indicator - shows only when isLoading is true --> <div ng-show="isLoading" class="loading-message"> <p>Processing your request, please wait...</p> <!-- You can add a spinning icon here too, like a Font Awesome spinner --> </div> <!-- Disable submit button while loading --> <button type="submit" ng-disabled="isLoading">Register User</button> </form>
Make the loading prompt look nicer with a bit of CSS. Here's a simple example:
.loading-message { padding: 12px; color: #555; font-style: italic; } /* If you use a spinner icon (e.g., Font Awesome) */ .loading-message i { margin-right: 8px; animation: spin 1.2s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
Right now your service uses callbacks, but AngularJS works great with Promises. Let's refactor the service to return a promise instead—it makes error handling cleaner:
// Refactored service code function Register(obj) { return $http({ method: 'POST', url: '/api/addUserOps', data: obj }).then(function(response) { return response.data; }, function(error) { // Pass the error along so the controller can handle it throw error.data; }); }
Then update your controller to use .then() and .catch()—plus .finally() ensures we turn off loading no matter if the request succeeds or fails:
$scope.submitRegistration = function(userObj) { $scope.isLoading = true; createUserService.Register(userObj) .then(function(data) { alertify.alert("Successfully Registered"); $state.reload(); }) .catch(function(error) { console.log("Check " + error); }) .finally(function() { // This runs whether the request succeeds or fails $scope.isLoading = false; }); };
That's it! Now your users will see a clear waiting message while the backend does its work, and they won't be able to accidentally submit the form multiple times.
内容的提问来源于stack exchange,提问作者Sharath B

