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

AngularJS中使用ng-repeat选中特定数据时设置布尔值的方法

解决AngularJS中选中特定数据时的输入值控制问题

嘿,我来帮你搞定这个AngularJS的问题~首先得先指出你原代码里的几个关键问题,然后给你一套能完美满足需求的解决方案:

先修正原代码的核心错误

你原代码里的$scope.obj定义完全不对:JavaScript对象里不能有重复的键,多个'id'键会被自动覆盖,最后只会剩下{id:3},根本没法实现循环多个数据项的需求。另外ng-repeat里的绑定也有问题,ctrl.myData没有对应到循环的每一项,没法正确存储输入值。

解决方案步骤

1. 调整数据结构

首先把数据改成数组格式,给每个项添加note字段用来存储输入框的内容,同时额外维护一个historyNotes对象,用来保存每个id的历史输入值,这样切换回之前的输入框时能恢复内容:

// 你的控制器代码
angular.module('myApp', [])
.controller('MyCtrl', function($scope) {
  // 正确的数组结构,每个元素包含id和当前输入的note
  $scope.obj = [
    { id: 1, note: '' },
    { id: 2, note: '' },
    { id: 3, note: '' }
  ];
  // 存储每个id的历史输入值,用于后续恢复
  $scope.historyNotes = {};
});

2. 编写HTML模板

给输入框绑定ng-change事件来处理输入逻辑,绑定ng-focus事件来恢复历史值:

<div ng-app="myApp" ng-controller="MyCtrl">
  <div ng-repeat="myData in obj track by myData.id">
    <input 
      type="text" 
      class="form-control" 
      placeholder="Notes" 
      ng-model="myData.note"
      ng-change="handleInputChange(myData)"
      ng-focus="restoreHistoryNote(myData)"
    >
  </div>
</div>

3. 实现核心逻辑函数

在控制器里添加两个函数,分别处理输入变化和历史值恢复:

// 处理输入变化的逻辑
$scope.handleInputChange = function(currentData) {
  // 这里判断:当操作的是id=1的输入框时,执行清空其他输入框的逻辑
  if (currentData.id === 1) {
    angular.forEach($scope.obj, function(item) {
      if (item.id !== 1) {
        // 先把当前输入值存入历史记录
        $scope.historyNotes[item.id] = item.note;
        // 清空当前显示的内容
        item.note = '';
      }
    });
  }
};

// 恢复历史输入值的逻辑
$scope.restoreHistoryNote = function(currentData) {
  // 如果当前不是id=1的输入框,且有历史记录,就恢复之前的内容
  if (currentData.id !== 1 && $scope.historyNotes[currentData.id]) {
    currentData.note = $scope.historyNotes[currentData.id];
  }
};

需求适配说明

如果你原本的需求是**当输入框的内容等于"1"(而不是操作id=1的输入框)**时,才触发清空其他输入框的逻辑,只需要修改handleInputChange的判断条件即可:

$scope.handleInputChange = function(currentData) {
  // 当输入框内容为"1"时触发(注意是字符串,若需要数字可转类型)
  if (currentData.note.trim() === "1") {
    angular.forEach($scope.obj, function(item) {
      if (item.id !== 1) {
        $scope.historyNotes[item.id] = item.note;
        item.note = '';
      }
    });
  }
};

这样就能完全满足你的需求:

  • 当触发条件时,保留id=1的输入值,其余输入框置空
  • 切换回之前操作过的输入框时,自动恢复之前输入的内容

内容的提问来源于stack exchange,提问作者Jydon Mah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:42:27