Javascript 如何在不中断角度数据绑定的情况下更新集合中的项目?

Javascript 如何在不中断角度数据绑定的情况下更新集合中的项目?,javascript,angularjs,angularjs-scope,lodash,angularjs-ng-options,Javascript,Angularjs,Angularjs Scope,Lodash,Angularjs Ng Options,我有一个对象集合,我想这叫做关联数组。无论如何,我想在列表中找到一个项目并更新它。作为旁注,该系列是select的ng模型。我知道lodash有一些这样的功能。我可以找到该项,但我不确定更新该项的最佳方式是什么,以便数据绑定仍能在我的select上工作 下面是一个不起作用的示例: for (x = 0; x < $scope.RulesTemplates.length; x++) { if($scope.RulesTemplates[x].Name == $scope.TempRu

我有一个对象集合,我想这叫做关联数组。无论如何,我想在列表中找到一个项目并更新它。作为旁注,该系列是select的ng模型。我知道lodash有一些这样的功能。我可以找到该项,但我不确定更新该项的最佳方式是什么,以便数据绑定仍能在我的select上工作

下面是一个不起作用的示例:

for (x = 0; x < $scope.RulesTemplates.length; x++)
 {
   if($scope.RulesTemplates[x].Name == $scope.TempRules.Name)
   {
     $scope.RulesTemplates[x] = $scope.TempRules;
   }
 }
for(x=0;x<$scope.RulesTemplates.length;x++)
{
if($scope.RulesTemplates[x].Name==$scope.TempRules.Name)
{
$scope.RulesTemplates[x]=$scope.TempRules;
}
}

尝试以下方法:

angular.forEach($scope.RulesTemplates, function(value, key){
    if(value.Name == $scope.TempRules.Name){
        value = $scope.TempRules;
    }
})

假设使用示例数据集,如果要扩展绑定到ng选项的数组中的现有对象,首先需要确保角度对象具有由特定唯一属性跟踪的数组项。然后您可以在相应的位置更新数组中的新项,angular将在绑定的选择选项中自动执行更新(无需重新呈现其他选项值)。但这种方法可能不会刷新已经绑定的ng模型

另一种使用传统循环的简单方法:-

<select ng-options="item.display for item in items" ng-model="selected"></select>


将确保在更新属性时基础源对象引用保持不变,您也可以使用lodash。

如何在视图中绑定它,是否正在查找angular.extend<代码>angular.extend($scope.RulesTemplates[x],$scope.TempRules)但是,如果您在ng repeat中,您可以使用带有唯一标识符的trackby,只需在执行时更新数组。使用ng选项。在我更新集合中的项之前,绑定一直有效。您能显示一些内容吗?浏览一下您的视图、模型或简单的plnkr。我们不知道您的数据模型是什么样子,也不知道您的选项是如何设置的,还有更多。。。这里还有一个PSL,你和往常一样都在这里。我认为extend这个例子对我很有用。将其作为要点的答案发布。非常感谢。
for (x = 0, l = $scope.items.length; x < l; x++){
  var item = $scope.items[x];
  if(item.name == itemsUpdate.name) {
      angular.extend(item,itemsUpdate); //Extend it
      break;
  }
}
var item = _.first($scope.items, {name:itemsUpdate.name}).pop(); //Get the item add necessary null checks
angular.extend(item, itemsUpdate);