【问题标题】:how can i update an item in a collection, without breaking angular databinding?如何在不破坏角度数据绑定的情况下更新集合中的项目?
【发布时间】:2014-10-15 23:14:51
【问题描述】:

我有一个对象集合,我认为这称为关联数组。无论如何,我想在该列表中找到一个项目并更新它。作为旁注,这个集合是一个选择的 ng-model。我知道 lodash 有一些这种类型的功能。我可以找到该项目,但我不确定更新项目的最佳方式是什么,因此数据绑定仍然适用于我的选择。

这是一个不起作用的例子:

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

【问题讨论】:

  • 你是如何在视图中绑定它的,你在找angular.extend吗? angular.extend($scope.RulesTemplates[x], $scope.TempRules); 但是,如果您在 ng-repeat 中,您可以使用带有唯一标识符的 trackby 并按照您的操作更新数组。
  • 使用 ng-options。在我更新集合中的项目之前,绑定一直有效。
  • 你能展示点什么吗?瞥见您的视图、模型或简单的 plnkr。我们不知道您的数据模型是什么样的,也不知道您的选项是如何设置的
  • option1 , option2 还有更多...这里还有一个option
  • PSL,你和往常一样。我认为扩展示例对我有用。将其发布为分数的答案。谢谢。

标签: javascript angularjs angularjs-scope lodash angularjs-ng-options


【解决方案1】:

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

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

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

你的更新逻辑可以是:-

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;
  }
}

Demo1

或者由于您使用的是lodash,因此代码行数可能会更少:-

var item = _.first($scope.items, {name:itemsUpdate.name}).pop(); //Get the item add necessary null checks
angular.extend(item, itemsUpdate);

Demo2

angular.extend 将确保底层源对象引用在更新属性时保持不变,您也可以使用 lodash merge

【讨论】:

    【解决方案2】:

    试试这样的:

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

    angular.forEach

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2022-01-26
      • 2010-12-21
      • 2022-12-22
      • 2021-04-14
      相关资源
      最近更新 更多