Reputation: 103
Okay i have a ng-repeat which displays multiple students data, now inside each ng-repeat i want to add a tag section, which will contain tags. So, basically their will be a input element which takes sag name and adds it to the tag section for that particular student.
// This is inside ng-repeat
<form>
<div id="tags">
</div>
<br>
<input id="tagvalue" ng-keypress="myFunct($event)" class="inputTag"
ng-model="addtags" placeholder="Add a tag">
</form>
// Inside Controller
$scope.myFunct = function(keyEvent) {
if (keyEvent.which === 13)
{
var value = document.getElementById('tagvalue')
var target = document.getElementById('tags');
var newElement = angular.element("<span class='badge'>"+value.value+"</span>");
angular.element(target).append(newElement);
this.addtags=""
}
}
The input field is created for all the students but tag section is working only for the first
Upvotes: 2
Views: 194
Reputation: 15031
You are using ID tags
for getting the reference before you create the <span>
element - and this id
is being repeated for each student, this is why tags would be added for the first student only;
You can take a different approach where you add these tags to the student object itself and then simply print the tags using a nested ng-repeat;
working snippet below:
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
$scope.studentsData = [{
name: 'Mr. one',
tags: []
}, {
name: 'Ms. two',
tags: []
}, {
name: 'Mr. three',
tags: []
}, {
name: 'Mr. four',
tags: []
}, {
name: 'Ms. five',
tags: []
}, ];
$scope.myFunct = function(keyEvent, indexNumber) {
if (keyEvent.which === 13 && this.addtags.length > 0) {
var value = document.getElementById('tagvalue');
$scope.studentsData[indexNumber].tags.push(this.addtags);
this.addtags = "";
}
}
});
.badge {
border: 1px solid red;
margin: 2px;
}
input {
float: right;
}
.students {
margin: 5px
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
<div class='students' ng-repeat='item in studentsData'>
Student Name: <b>{{item.name}}</b>
<ng-container id="tags" ng-repeat='tag in item.tags' class='badge'>
<span> {{tag}} </span>
</ng-container>
<input id="tagvalue" ng-keypress="myFunct($event, $index)" class="inputTag" ng-model="addtags" placeholder="Add a tag">
</div>
</form>
</div>
Upvotes: 1