假设我有一个来自数据库的 Javascript 动态数组:
customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...]
和输入:
<input type='text' name="forJohnOnly" ng-model="customers[0].name" />
<input type='text' name="forTimOnly" ng-model="customers[1].name" />
该数组来自已排序的数据库,John 始终是第一项。虽然这有效,但我不喜欢它,因为有人可能会在不更新 UI 的情况下更改数据库中的排序顺序,并且第一个输入现在包含 Tim 的名字,这是错误的。这个相同的数组被发送回后端以保存在数据库中。
我正在尝试执行如下所示的操作,其中动态确定正确的索引,而无需为此目的创建额外的数组并在两个数组之间进行复制
<input type='text' name="forJohnOnly" ng-model="customers[where customers.id=1].name" />
<input type='text' name="forTimOnly" ng-model="customers[where customers.id=2].name" /> (need to use id because name can be updated)
有什么想法吗?
更新:
虽然数据位于数组中,但文本框并不采用统一布局(例如网格)。
最佳答案
编写一个接收 id 并返回对象的函数。像这样的事情
function getRow(id) {
customers.forEach(itm => if(itm.id == id){ return itm; });
}
并在 html 中使用它,例如
<input type='text' name="forJohnOnly" ng-model="getRow(customer.id).name" />
或者使用像这样的ng-repeat
<div ng-repeat="customer in customers">
<input type='text' name="{{customer.name}}Only" ng-model="customer.name" />
</div>
然后按照您想要的顺序对 customers
数组进行排序即可!
关于javascript - 如何对数组中的特定项目进行双向数据绑定(bind),其中数组索引是动态确定的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50382463/