首页 \ 问答 \ 在AngularJS中将值从表单推送到数组时避免使用Dupes(Avoiding Dupes when pushing values from form to array in AngularJS)

在AngularJS中将值从表单推送到数组时避免使用Dupes(Avoiding Dupes when pushing values from form to array in AngularJS)

我在使用代码避免欺骗时遇到问题。 这是一个简化的例子。 我知道问题在于数组对象是同一范围变量的引用,但是避免它的最佳方法是什么?

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
      $scope.items.push($scope.item);
    }
  });
</script>

这是一个演示问题的小提琴: http//jsfiddle.net/u8Fuk/8/


I'm having problems avoiding dupes with my code. Here is a simplified example. I know the problem is in the array object being a reference of the same scope variable, but what is the best way to avoid it?

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
      $scope.items.push($scope.item);
    }
  });
</script>

Here is a fiddle that demonstrates the problem: http://jsfiddle.net/u8Fuk/8/


原文:https://stackoverflow.com/questions/20836251
更新时间:2020-10-17 18:10

最满意答案

取决于你的目标是什么。

如果要允许重复值,则需要更改代码,因为ngRepeat中的每个项都必须具有唯一ID。 请在此处查看track by部分。

这将是这样的:

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item.value }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
        $scope.items.push({value:$scope.item});
    }
  });
</script>

请在此处查看更新的小提琴。

如果您不想允许相同的值,则需要搜索它。

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
      var found = $scope.items.reduce(function(previous, i){
          if ($scope.item === i) return true;
          return previous;
        }, false);
      if (found){
        alert('duplicate value');
      }
      else{
        $scope.items.push($scope.item);
      }
    }
  });
</script>

请在此处查看更新的小提琴。


Depends on what your goal is.

If you want to allow for duplicate values you need to change the code a bit as each item in the ngRepeat has to have a unique id. See the track by section here.

That would work like this:

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item.value }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
        $scope.items.push({value:$scope.item});
    }
  });
</script>

See the updated fiddle here.

If you don't want to allow for the same values you need to search for it.

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <input type="text" ng-model="item" />
    <div ng-repeat="item in items">
      {{ item }}
    </div>
    <button ng-click="save()">Save</button>
  </div>
</div>
<script>
  angular.module('myApp', []).
  controller('myCtrl', function ($scope) {
    $scope.items = [];
    $scope.save = function() {
      var found = $scope.items.reduce(function(previous, i){
          if ($scope.item === i) return true;
          return previous;
        }, false);
      if (found){
        alert('duplicate value');
      }
      else{
        $scope.items.push($scope.item);
      }
    }
  });
</script>

See the updated fiddle here.

2013-12-30

相关问答

更多

http://errors.angularjs.org/1.4.1/ngRepeat/dupes(http://errors.angularjs.org/1.4.1/ngRepeat/dupes)

像这样使用: <tr ng-repeat="blog in blogs track by $index"> <td>{{ blog.title }}</td><td>{{ blog.description }}</td><td>{{ blog.added_date }}</td><td><button class="btn btn-danger" ng-click="removeData(blog.id)">x</button></td> </tr> 有关dupe的详细信息, 请查看An ...

Angular ngRepeat:dupes错误(尽管没有重复的键)(Angular ngRepeat: dupes error (although there are no duplicate keys))

你的两个服务电话之间有竞争条件。 最后完成的是将其结果分配给$ scope.topics。 我假设对用户服务的调用应如下所示: usersFactory.index(function(data){ $scope.users= data; }) You've got a race condition between your two service calls. Whichever finishes last is going to assign its results to $sco ...

Drupal7 Dupes Error中的AngularJS ng-repeat(AngularJS ng-repeat in Drupal7 Dupes Error)

我解决了 我的D7模块的JavaScript文件中有一个非常愚蠢的错误。 (注意:请参阅上面的JSFiddle以了解变量及其数据) 我的错误是这样的; $scope.DATA = $filter('json')(data); 它指定一个'字符串'而不是'JSON对象',因此'ng-repeat'会在迭代时拾取一个字符数组,从而导致重复错误,因此它解释了为什么当我尝试'track by'时,为什么我无法使表达式工作(仅仅因为对象不存在),以及div等的三倍,因为它是一个逐字符地进行评估的字符串。 注 ...

使用AngularJS将输入值从ng-repeat推入数组(Pushing input values from ng-repeat into array with AngularJS)

诀窍是在ng-repeat 为每个重复元素输入一个输入。 <div ng-repeat="pa in products"> {{pa.nom}} <input type="number" ng-model="pa.basket"> </div> <a ng-click="insert()">Add items</a> insert()将循环播放产品,并在篮子已设置时插入singleOrder : $scope.insert = function() { for (var ...

在推入AngularJs时,对象被覆盖(Objects are being overwritten when pushing in AngularJs)

试试这个会起作用: var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl',function ($scope) { $scope.model={ salary:'', position:'', user: [{ name:'', address:'' }] } $scope.submitFu ...

使用AngularJS将值推送到json文件(pushing values to a json file with AngularJS)

你可以改变$scope.name作为一个数组,如: angular.module('MyApp',['ngMaterial', 'ngMessages','material.svgAssetsCache']) .controller('AppCtrl', function($scope) { $scope.names = [] $scope.setValue = function (metaName) { $scope.names.push(metaName); ...

将范围表单推送到更改阵列的其他成员的数组(Pushing scope form to array changing other members of the array)

您正在推送对象的引用,这不是深层克隆 You are pushing a reference to object, this is not a deep clone

将值推送到AngularJS数组(Push values to array AngularJS)

尝试这样做: $scope.test = []; $scope.test.push($scope.form); Try doing this: $scope.test = []; $scope.test.push($scope.form);

AngularJS $ rootScope:infdig和ngRepeat:dupes(AngularJS $rootScope:infdig and ngRepeat:dupes)

你的ng-repeat依赖于一个scope函数,它每次运行都会返回一个新的数组。 即使返回值在内部每次都是等效的,它仍然是一个不同的对象(即函数不是幂等的)。 这会导致另一个$ digest循环运行,返回另一个值,导致它再次运行,依此类推。 如果不加以控制,它会永远持续下去。 这就是您看到错误的原因。 这行代码是你的问题: {{loadBranches(section.sectionName)}} ...与随附的控制器代码一起使用。 解决方案是初始化$scope.branches : Secti ...

在AngularJS中将值从表单推送到数组时避免使用Dupes(Avoiding Dupes when pushing values from form to array in AngularJS)

取决于你的目标是什么。 如果要允许重复值,则需要更改代码,因为ngRepeat中的每个项都必须具有唯一ID。 请在此处查看track by部分。 这将是这样的: <div ng-app="myApp"> <div ng-controller="myCtrl"> <input type="text" ng-model="item" /> <div ng-repeat="item in items"> {{ item.value }} </div> <b ...

相关文章

更多

最新问答

更多
  • 一个Web角色上的两个Web应用程序 - 配置问题(Two web applications on one Web Role - config issue)
  • Chrome扩展程序:在后台页面中存储变量是否安全?(Chrome extension : storing variables in background page is secure?)
  • C ++ 11中的atomics是否阻止编译器重新读取共享变量?(Do atomics in C++11 prevent compiler to re-read from shared variables?)
  • Java代码重组(Java code restructuring)
  • 从video.js获取currentTime(Get currentTime from video.js)
  • 3列 - 带溢流元件的中心柱流体(3 columns - center column fluid with an overflow element)
  • JSX节点中的TypeScript类型参数(TypeScript type arguments in JSX nodes)
  • .NET自定义事件组织帮助(.NET custom event organization assistance)
  • 如何将内存地址(如0xc20803a000)转换为字符串?(How to convert memory address (like 0xc20803a000) to string? Golang)
  • 从python中的列表创建新列表的最佳方法(Best way to create a new list from a list in python)
  • 为什么RabbitMQ会从破坏的持久性日志文件中脱颖而出?(Why does RabbitMQ keep breaking from a corrupt persister log file?)
  • 将对象添加到模型中,不更新dom(Adding object to model, doesn't update dom)
  • 将array.count转换为String(Convert array.count to String)
  • Chrome中的HTML (HTML in Chrome)
  • Sklearn:分类Imputer?(Sklearn: Categorical Imputer?)
  • 为什么iOS 9方法仍适用于iOS 8.4?(Why Do iOS 9 Methods Still Work on iOS 8.4?)
  • 输入类型文件无法获取angularjs中文件类型的文件名(input type file is unable to get the file name with file type in angularjs)
  • 为什么SplFixedArray的json_encode转储对象而不是数组?(Why does json_encode of a SplFixedArray dump an object instead of an array?)
  • ORA-01858:找到一个非数字字符,其中xp.executenonquery()上的数字是预期的(ORA-01858: a non-numeric character was found where a numeric was expected on xp.executenonquery())
  • 通过使用sscanf提取数据在BST插入函数中传递参数(Passing arguments in a BST insert function by extracting data using sscanf)
  • 混合c和c ++的问题(problem mixing c and c++)
  • 检查几个选项的文本(Checking text against several options)
  • 在Flex中创建Captch组件(Create Captch Component in Flex)
  • 查询非常复杂,不确定是否可能。(Very complicated query, not sure if it possible. Involves not adding to a running sum)
  • AOSP - networkAttributes中CSV的含义(AOSP - Meaning of CSV in networkAttributes)
  • 将不同表中的数据拖入单个视图中(Pulling data from different tables into a single view)
  • 从Enum Java调用随机值(更新)(Calling Random Value from an Enum Java)
  • jwplayer与vimeo插件(jwplayer with vimeo plugin)
  • CSS依赖于ActiveX?(CSS dependent on ActiveX?)
  • TPL Dataflow没有完成多个目标(TPL Dataflow not completing with multiple targets)