繁体   English   中英

AngularJS推送具有不同值的项目

[英]Angularjs push items with different values

我有一个json,其中我使用ng-repeat在列表中显示了一些值。 当我单击列表中的一个项目时,我将该项目添加到一个空数组中,然后循环使用push方法创建表单的某些文件。 用户只需单击第一个数组即可创建他想要的所有字段。 问题是,如果我推送两个或多个相同的项目,那么我在表格的输入文本中所写的内容将在所有相同的输入中重复。 我需要的是,即使相同,所有字段都是独立的。 我在这里创建了一个jsfiddle: https ://jsfiddle.net/k6s357L8/8/感谢您的帮助

 var myApp = angular.module('myApp',[]); myApp.controller("mycontroller", ["$scope", "$http", function($scope, $http){ $scope.getItems = { "data": [ { "label": "first", "objects": [ { "name": "firstObj", "attributes": [ { "attrname": "asd1", "attrValue": "", "attrType":"text" }, { "attrname": "asd2", "attrValue": "", "attrType":"text" } ] } ], "key": "bolla" }, { "label": "second", "objects": [ { "name": "secondObj", "attributes": [ { "attrname": "asd", "attrValue": "", "attrType":"text" }, { "attrname": "asd3", "attrValue": "", "attrType":"text" } ] } ], "key": "2" } ] }; $scope.filterSelected = $scope.getItems.data[0].objects; $scope.myNewArray = { newArray: [ ] } $scope.pushItems = function pushItems(items) { $scope.myNewArray.newArray.push(items); console.log($scope.myNewArray); } }]); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app='myApp' ng-controller='mycontroller'> <div data-ng-repeat="item in myNewArray.newArray track by $index"> <div ng-if="item.attrType == 'text'"> <input id="form-f{{$index}}" type="text" placeholder="{{item.attrname}}" data-ng-model="item.attrValue"/> </div> </div> <div data-ng-repeat="object in getItems.data"> <div data-ng-repeat="att in object.objects"> <ul ng-repeat="data in att.attributes"> <li> <a ng-click="pushItems(data)">{{data.attrname}}</a> </li> </ul> </div> </div> </div> 

您可以使用angular.copy克隆对象:

$scope.pushItems = function pushItems(items) {
    $scope.myNewArray.newArray.push(angular.copy(items));
    console.log($scope.myNewArray);
}

看到这个小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM