How to repeat duplicate objects using ng-repeat in AngularJs? - angularjs

This is my code.
$scope.data=[];
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}];
$scope.addFields = function (field) {
$scope.data.push(field);
};
This is my html:-
<div ng-repeat="eachItem in data">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" ng-model="fieldValue"/>
</div>
when i click add button push one more object into $scope.data array like
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"},{"label":"name","type":"string"}];
In the above i got an error
angular.min.js:102 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.14/ngRepeat/dupes?p0=nestedField%20in%20fieā€¦%2C%22type%22%3A%22string%22%2C%22%24%24hashKey%22%3A%22object%3A355%22%7D
at Error (native)
I have duplicate objects after adding. because i want to repeat label names using ng-repeat in angularjs.First i have output like this
OutPut:-
name textbox
email textbox
After add button click Output:-
name textbox
email textbox
name textbox

use track by $index
var app = angular.module("app",[])
app.controller('ctrl',['$scope', function($scope){
$scope.data=[];
$scope.data=[{"label":"name","type":"string"},{"label":"email","type":"string"}];
$scope.addFields = function (field) {
$scope.data.push(field);
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div class="item item-checkbox">
<div ng-repeat="eachItem in data track by $index">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" />
</div>
</div>

Use track by for this purpose.
<div ng-repeat="eachItem in data track by $index">
<input type="button" value="add" ng-click="addFields(eachItem)"/>
<label>{{eachItem.label}}</label>
<input type="text" ng-model="eachItem.value" />
</div>
You also able to use track by with your custom filed, like id, or whatever
Important: It's better to use track by in each ng-repeat, cause it's improve ng-repeat's performance (read more).
But avoid to use track by in ng-options and other cases when you use select as .. for ... construction (read more)
JsFiddle here

You have to ensure that items in the array have an unique key. If that is not possible you can use track by $index in the ng-repeat.
Check the details here

Related

get values from each ng-repeat input elements

I have the following code where I have added 5 input texts via ng-repeat and now am trying to fetch each of the input element's values. I am hitting some roadblock, so please help me out on how to fetch individual values.
HTML:
<form class="quick-add-form" method="post">
<label class="quick-add-label">Enter the catalog number and quantity</label>
<div class="quick-add">
<div class="catalog-list">
<label class="catalog-number-label" for="catalog-number-input">Catalog Number:</label>
<div ng-repeat="values in catalogNumber(number) track by $index">
<input id="catalog-number-input-{{$index}}" class="catalog-number-input"
type="text" ng-model="catalog.description" validate-input>
</div>
</div>
<div class="qnty-list">
<label class="pdt-qnty-label" for="pdt-qnty-input">Quantity:</label>
<div ng-repeat="values in catalogNumber(number) track by $index">
<input id="pdt-qnty-input-{{$index}}" class="pdt-qnty-input" type="number" pattern="[0-9]*"
inputmode="numeric" min="1" max="999" ng-model ="catalog.quantity" name="qty"
maxlength="3">
</div>
</div>
</div>
<div>
<button type="submit" class="btn btn-danger cta-button quick-add-btn"
ng-click ="quickAdd(catalog)">Add to List</button>
</div>
</form>
and controller:
$scope.catalog = {};
$scope.catalogNumber = catalogNumber;
$scope.initializeModal = initializeModal;
$scope.quickAdd = quickAdd;
function catalogNumber(num) {
return new Array(num);
}
function quickAdd(val) {
console.log(val);
}
function init() {
$scope.number = 5;
$scope.catalog.quantity = 1;
}
I am pretty sure its because of indexing and which is why by adding value in one input, its adding same value in all at once. But I am not sure how/where to use the $index properly to achieve the result.
Thanks.
Perhaps a better way would be to use the model? For example:
<div ng-repeat="values in catalogNumber(number) track by $index">
<input
id="catalog-number-input-{{$index}}"
class="catalog-number-input"
type="text"
ng-model="catalog.description[$index]"
validate-input>
</div>
Now in your controller:
catalog.description = [];
Then you have an array of objects, which you can perform your math on:
var total = _.sum(Object.values(catalog.description));
Edit: I had forgot I was using Lodash/Underscore there, but if you wanted to use standard JS you could use a standalone method, or reduce etc.,

post data inside clone div angularjs ng-model

Clone div is repeating, when I click add button.
How can I post the fields inside clone div.
<div class="row" id="append-row">
<div class="clone-div-{{count}}" id="clone-div">
<div class="col-md-6">
<div class="form-group input-group-sm">
<label>Title</label>
<input type="text" class="form-control" id="addTitle" placeholder="Title" ng-model="chapters.chapter.title">
</div>
</div>
<div class="col-md-6">
<div class="form-group input-group-sm">
<label>Select Language</label>
<select class="form-control" name="country" id="country" ng-model="chapters.chapter.languageID" ng-options="value.ID as value.language for value in technical.languages">
<option value="">Select Country</option>
</select>
</div>
</div>
</div>
</div>
This part is angularjs code.
$scope.count = 1;
$scope.addChapter = function() {
var iEl = angular.element( document.querySelector('#append-row') );
var wEl = angular.element( document.querySelector('#clone-div') );
iEl.append(wEl.clone());
$scope.count+=1;
};
You should do cloning/repeating inside the template in a ng-repeat and have the data prepared beforehand, that is a much cleaner way. You'll notice for example in the template code you have, all the ng-model's are the same, and will always display the same information if you have 1 'clone' div or 100.
A better method would be to write your clone div in the template and use it as a repeatable ng-template 'script', for example:
// main template
<script type="text/ng-template" id="cloneable.html">
// Your code here, but change reference to ng-model, ie this line as an example:
<input type="text" class="form-control" id="addTitle" placeholder="Title" ng-model="chapters.chapter[$index].title">
</script>
// main template, your new repeat then includes the repeatable script
<div ng-repeat="foo in manyFoos"
ng-include="'cloneable.html'"></div>
This way you can use the $index that arises from ng-repeat, as part of the model to accurately separate each individual repeat block. In your controller, chapters.chapter will be an array of objects.
I don't know about the 'add' button part or what information you're adding, but the above should take care of the model problem you'll be encountering.

ng-model in ng-repeat - how to send values to server

im using ng-repeat to create dynamic number of textboxs.
<div class="orgevent" ng-repeat="i in getNumber(numOfEvents) track by $index">
<input class="dest" type="text" value="Free text" ng-model="i.freeText">
</div>
i want (on click) to take the values that the user write in the textBox and send it to the server,
how can i do it?
i tried to take it in the JS by ng-model but the value is always "undefined"
You can use ng-model as array and read it on click. Take a look
http://jsfiddle.net/ucskyv67/74/
app.controller("cookieCtrl", function ($scope, $cookies) {
$scope.numbers= [1,2,3,4,5,6];
$scope.userVals=[];
$scope.getVal= function(){
console.log($scope.userVals);
}
});
<div ng-app="cookieApp" ng-controller="cookieCtrl">
<div class="orgevent" ng-repeat="i in numbers track by $index">
<input class="dest" type="text" value="Free text" ng-model="userVals[$index]">
</div>
<button ng-click="getVal()">Read</button>
</div>
one option is to add ng-change to your input and implement a method in your controller to call the server-
<input ng-change="handleChange(i.freeText)" class="dest" type="text" value="Free text" ng-model="i.freeText">

ng-models name collision inside ng-repeat

http://plnkr.co/edit/2UFfaG?p=preview
I used this sample code to build a simple app and I noticed that the edit function doesn't work when you are using ng-models that are repeated in a loop. I know this, because I tried using ng-models outside of the ng-repeat loop and it worked perfectly. So when you have two instances of ng-models with the same name, you get a blank data back when you try to get the values back from the view.
This is my view:
<ul ng-repeat="notes in notes">
<li>
<span ng-hide="editing" ng-click="editing = true">{{note.name}} | {{note.content}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="name" placeholder="Name" ng-required/>
<label>Content:</label>
<input type="date" ng-model="content" placeholder="Content" ng-required/>
<br/>
<button class="btn" ng-click="edit(note.id)">Save</button>
</form>
</li>
</ul>
This is my edit method:
$scope.edit = function (id) {
var note = notesRef.child(id);
var newNote= {
name : $scope.name,
content : $scope.content
}
};
note.update(newNote);
};
When I refer to a ng-model inside of ng-repeat, I can only get the value null for some reason. I get the correct value when I refer to ng-models outside of the ng-repeat for some reason.
How do we solve this problem? What's the simplest solution?
The problem is that the item belongs to the scope of the repeat.
If you changed your ng-model to:
<ul ng-repeat="notes in notes">
<li>
<span ng-hide="editing" ng-click="editing = true">{{note.name}} | {{note.content}}</span>
<form ng-show="editing" ng-submit="editing = false">
<label>Name:</label>
<input type="text" ng-model="note.name" placeholder="Name" ng-required/>
<label>Content:</label>
<input type="date" ng-model="note.content" placeholder="Content" ng-required/>
<br/>
<button class="btn" ng-click="edit(note)">Save</button>
</form>
</li>
</ul>
Where it's now note.name / note.content.
Then instead of padding the note.id to the edit button, you pass in the entire note i.e ng-click="edit(note)"
Then your controller will get passed the entire note.
$scope.edit = function (note) {
// send note to server via $http, changes to `note` are already made directly to the note itself
};
Hope that makes sense.
it should be like this. As we know ng-repeats directive create their own new scope.
bday.editing
<ul ng-repeat="bday in bdays">
<li>
<span ng-hide="bday.editing" ng-click="bday.editing = true">{{bday.name}} | {{bday.date}}</span>
<form ng-show="bday.editing" ng-submit="bday.editing = false">
<label>Name:</label>
<input type="text" **ng-model="bday.name"** placeholder="Name" ng-required/>
<label>Date:</label>
<input type="date" **ng-model="bday.date"** placeholder="Date" ng-required/>
<br/>
<button class="btn" type="submit">Save</button>
</form>
</li>
</ul>
and here what I understand from your question is that you want to edit only the item on which you have click. this is the solution for the same.
One more solution for the same problem is that create a new function that take one argument that is "bday". make edit true only for this item and set editing false for all others element. this solution is for that case if user doesn't submit the form and click on other item.

Angular.JS: why can't the inputs be edited?

This is a strange problem. The code is simple:
HTML code:
<body ng-controller="MainCtrl">
<ul ng-repeat="name in names">
<input type="text" ng-model="name" />
</ul>
</body>
Angular code:
app.controller('MainCtrl', function($scope) {
$scope.names = ["aaa","bbb","ccc"];
});
The live demo url is: http://plnkr.co/edit/2QFgRooeFUTgJOo223k9?p=preview
I do not understand why the input controls can not be edited, I can't type new characters or delete characters.
This is a common issue due to scope inheritance . Each of your names is a primitive so ng-repeat makes it's own scope item that is not connected to original, however if each names is an object ng-repeat scope item will be a reference to original object
[{name:"aaa"},{name:"bbb"},{name:"ccc"}];
Always use a dot in ng-model is a helpful rule of thumb
<div ng-repeat="item in names">
<input type="text" ng-model="item.name"/>
</div>
Working Plunker
Read this article on angular github wiki for detailed explanaton:
https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance
Angular 'fixed' this in 1.1 with the track by $index. No need to change your model.
<div ng-repeat="item in names track by $index">
<input type="text" ng-model="names[$index]" />
</div>
Plunker here
Late answer, but you should also be careful of typos, that angular will not warn you about:
<div ng-repeat="item in names track by $index" ng=if="names[$index] = 'John'">
<input type="text" ng-model="names[$index]" />
</div>
Note the single equals in the ng-if, that will not cause a warning or error, but the text will also be read only. Quite a hard one to spot if you are reading quickly.
It of course should be:
<div ng-repeat="item in names track by $index" ng-if="names[$index] == 'John'">
<input type="text" ng-model="names[$index]" />
</div>

Resources