AngularJS:点击编辑按钮启用文本框正常,请求实现成功响应后隐藏文本框
Solution: Hide Text Input After AngularJS API Success
Hey, great job getting the edit toggle working so far! Let's get that save-and-hide functionality sorted out—it's pretty straightforward once you hook into your API success callback. Here's how to do it step by step:
1. Update Your HTML to Add a Save Button
First, modify your table cell to show a "Save" button when in edit mode (and hide the Edit button). This gives users a way to submit their changes:
<tr ng-repeat="data in Value" > <td> <span ng-show="!data.edit">{{data.question}}</span> <input ng-show="data.edit" type="text" ng-model="data.question" class="form-control" placeholder="Name"/> </td> <td>{{data.name}}</td> <td> <!-- Show Edit button when not editing --> <button ng-show="!data.edit" ng-click="editUtterance(data)" class="glyphicon glyphicon-pencil edit">Edit</button> <!-- Show Save button when editing --> <button ng-show="data.edit" ng-click="saveUtterance(data)" class="glyphicon glyphicon-floppy-disk save">Save</button> </td> </tr>
2. Add a Save Function in Your AngularJS Controller
Next, create a saveUtterance function in your controller that calls your API, and sets data.edit = false in the success callback to hide the text input. Here's an example using AngularJS's $http service:
// Your existing edit function (keeps the input visible) $scope.editUtterance = function(data) { data.edit = true; }; // New save function to submit changes and hide the input $scope.saveUtterance = function(data) { // Replace this with your actual API endpoint and request logic $http.put(`/api/utterances/${data.id}`, { question: data.question, name: data.name // Include any other fields you need to update }) .then(function(apiResponse) { // Success! Flip the edit flag to hide the input and show the span data.edit = false; // Optional: Add a success message for the user // $scope.successMessage = "Utterance updated successfully!"; }) .catch(function(apiError) { // Handle API failure (don't hide the input so user can retry) console.error("Failed to save changes:", apiError); // Optional: Show an error message to the user // $scope.errorMessage = "Oops, something went wrong. Please try again."; }); };
Key Notes
- The core logic is simple: when your API responds successfully, toggle the
data.editproperty back tofalse. AngularJS'sng-showdirectives will automatically update the DOM to hide the input and show the static text. - Make sure your API endpoint correctly accepts the updated data (in this example, we're using a
PUTrequest to update an existing resource). Adjust the HTTP method and payload to match your backend setup. - If you're using a custom service instead of raw
$http, the same logic applies—just setdata.edit = falseinside the service's success callback.
内容的提问来源于stack exchange,提问作者My Test
相关产品推荐
相关产品推荐

