You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. String vs. Boolean Mismatch
    You're using string values ('false'/'true') for your edit variable, but Angular's ng-show relies on boolean logic. In JavaScript, any non-empty string is considered "truthy"—so when you check edit != true:

    • When edit is 'false', 'false' != true evaluates to true (since the types don't match), so your span stays visible.
    • When you set edit to 'true', 'true' != true also evaluates to true, so the span never hides. That's why your original span won't disappear!
  2. Global Edit State Controls All Rows
    You're using a single $scope.edit variable for all rows generated by ng-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 edit variable, we add an edit boolean property directly to each data object in your Value array. This lets each row control its own edit state independently.
  • Boolean Logic for ng-show: We use !data.edit (boolean negation) and data.edit directly, which aligns with Angular's expected boolean values for ng-show.
  • Simplified Click Handler: Pass the entire data object to editUtterance instead 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 forEach loop 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:44:44