AngularJS行内编辑行失效:点击编辑按钮后输入框全激活且元素未隐藏
Fixing AngularJS Inline Edit Issues (All Fields Activate + Span Won't Hide)
Let's break down what's going wrong here and fix it step by step:
Core Problems in Your Code
String vs. Boolean Mismatch
You're using string values ('false'/'true') for youreditvariable, but Angular'sng-showrelies on boolean logic. In JavaScript, any non-empty string is considered "truthy"—so when you checkedit != true:- When
editis'false','false' != trueevaluates totrue(since the types don't match), so your span stays visible. - When you set
editto'true','true' != truealso evaluates totrue, so the span never hides. That's why your original span won't disappear!
- When
Global Edit State Controls All Rows
You're using a single$scope.editvariable for all rows generated byng-repeat. This means clicking any edit button will toggle the state for every row at once, which is why all input fields activate together.
Corrected Code
Controller Code
// Remove the global $scope.edit variable—we'll track edit state per row instead $scope.editUtterance = function(data){ // Optional: Close edit state for all other rows (if you want only one row editable at a time) $scope.Value.forEach(item => { if(item !== data) item.edit = false; }); // Toggle the edit state for the clicked row data.edit = !data.edit; console.log(data.edit); }
HTML Template
<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>{{dataId.name}}</td> <td> <span ng-click="editUtterance(data)" class="glyphicon glyphicon-pencil edit"></span> </td> </tr>
Key Changes Explained
- Per-Row Edit State: Instead of a global
editvariable, we add aneditboolean property directly to eachdataobject in yourValuearray. This lets each row control its own edit state independently. - Boolean Logic for ng-show: We use
!data.edit(boolean negation) anddata.editdirectly, which aligns with Angular's expected boolean values forng-show. - Simplified Click Handler: Pass the entire
dataobject toeditUtteranceinstead of just the ID—this makes it easy to update the row's edit state directly (you can still use IDs if needed, but passing the object is cleaner). - Optional Single-Row Edit: The
forEachloop closes edit state for other rows if you want to restrict editing to one row at a time. Remove this if you want multiple rows editable simultaneously.
内容的提问来源于stack exchange,提问作者My Test
相关产品推荐
相关产品推荐

