How to use Nested ng-repeat to repeat table columns dynamically? - angularjs

I want to make dynamic columns of a table and create a new object to save it in mongoDb.
I have first Array of Student as:
students = [{id: "1", name: "abc"},{id: "2", name: "def"},{id: "3", name: "hij"}]
and have second Array of Subjects as:
subjects = [{sName: "maths"},{sName: "science"}]
Here is the HTML
<div ng-app='t' ng-controller='test'>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th ng-repeat="subject in subjects">{{subject.sName}}</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in finalData track by $index">
<th><input type="text" ng-model="row.rollNo"/></th>
<th><input type="text" ng-model="row.fullName"></th>
<th ng-repeat="subject in subjects"><input type="text" ng-model="row.marks"></th>
<th>
<button ng-click="action($index)">
add/remove
</button></th>
</tr>
</tbody>
</table>
</div>
Here is the Controller
(function(){
var app = angular.module('t', []);
app.controller('test',
[
'$scope',
function($scope)
{
$scope.students = [{id: "1", name: "abc"},{id: "2", name: "def"},{id: "3", name: "hij"}]
$scope.subjects = [{sName: "maths"},{sName: "science"}]
$scope.finalData = new Array();
$scope.finalData.push({
icon : false
});
$scope.action=function(index){
if(index == $scope.finalData.length-1){
$scope.finalData[index].icon = true;
$scope.finalData.push({
icon : false
});
}else{
$scope.finalData.splice(index, 1);
}
};
}
]);
})();
The Output Looks like this.
The marks columns are repeating similar values. But i want one single finalObject to save my data.
Here is the jsFiddle of my problem https://jsfiddle.net/g8tn71tr/

The row subjects refer to the same NgModel row.marks which makes them have the same value.
You can solve it by making the ng-model refer to each of the subjects ng-model="row.marks[subject.sName]". This will result in that row.marks will become an object where each subject will be a key and the model will be in its value
(function(){
var app = angular.module('t', []);
app.controller('test',
[
'$scope',
function($scope)
{
$scope.students = [{id: "1", name: "abc"},{id: "2", name: "def"},{id: "3", name: "hij"}]
$scope.subjects = [{sName: "maths"},{sName: "science"}]
$scope.finalData = new Array();
$scope.finalData.push({
icon : false
});
$scope.action=function(index){
console.clear();
console.log($scope.finalData[index]);
if(index == $scope.finalData.length-1){
$scope.finalData[index].icon = true;
$scope.finalData.push({
icon : false
});
}else{
$scope.finalData.splice(index, 1);
}
};
}
]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='t' ng-controller='test'>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th ng-repeat="subject in subjects">{{subject.sName}}</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in finalData track by $index">
<th><input type="text" ng-model="row.rollNo"/></th>
<th><input type="text" ng-model="row.fullName"></th>
<th ng-repeat="subject in subjects"><input type="text" ng-model="row.marks[subject.sName]"></th>
<th>
<button ng-click="action($index)">
add/remove
</button></th>
</tr>
</tbody>
</table>
</div>

Related

ng-click is not working in table header

Hi I am new to AngularJS. I am creating a sample application to sort the data in a table by clicking the table header. On the first click it should arrange it in ascending order. Second click it should arrange it to descending.
Below provided are the cshtml code.
<div ng-controller="myController">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th ng-click="sortData('firstname')">First Name</th>
<th>Last Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees|orderBy:'sortColumn'">
<td>{{employee.firstname | lowercase}}</td>
<td>{{employee.lastname| uppercase}}</td>
<td>{{employee.salary |currency:"$":1}}</td>
</tr>
</tbody>
</table>
</div>
Below provided are script for module
var myApp = angula
.module("myModule", [])
.controller("myController", function ($scope) {
var employee = [
{ firstname: "First", lastname: "Trueman", salary: "20001" },
{ firstname: "Second", lastname: "someone", salary: "20002" },
{ firstname: "Third", lastname: "apple", salary: "20003" },
{ firstname: "Fourth", lastname: "parrot", salary: "20004" },
{ firstname: "Fifth", lastname: "mat", salary: "20005" },
];
$scope.employees = employee;
$scope.sortColumn = "firstname";
$scope.reverseSort = false;
$scope.sortData = function (column) {
$scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
});
For some reason ng-click is not working. Does anyone face the same issue before., If yes can you help me with this.
There were two things needed to be fixed:
sortColumn should be used without the single quote as it is a variable
add reverseSort variable to the orderBy.
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th ng-click="sortData('firstname')">First Name</th>
<th>Last Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="employee in employees|orderBy: sortColumn : reverseSort">
<td>{{employee.firstname | lowercase}}</td>
<td>{{employee.lastname| uppercase}}</td>
<td>{{employee.salary |currency:"$":1}}</td>
</tr>
</tbody>
I've created a working plnkr here.

AngularJS Table Custom Search Filter Per Column

I am looking for help in creating a custom filter that will work on any table that has a search property.
So far, I can get the table to filter based on what is input into each column search bar, but I can't figure out how to implement a 'startsWith' for each column as well so that it will only find 'Florida' if you type 'Flor' or 'Fl', etc. instead of finding it when typing 'lor' or 'ida'.
I have been able to get just one column working with a custom filter, but lost on how to implement this for multiple columns.
Here is the plunkr example: http://plnkr.co/edit/CE3uhZmksiepmVL2bLNF?p=preview
Script:
var app = angular.module("stateManagement", []);
app.controller("myCtrl", ["$scope", myCtrl]);
function myCtrl($scope) {
$scope.names = [{
Name: "Florida",
Country: "USA"
}, {
Name: "Texas",
Country: "USA"
}]
$scope.state = '';
$scope.elements = [{
state: "Florida"
}, {
state: "Texas"
}];
}
app.filter('myfilter', function() {
function strStartsWith(str, prefix) {
return (str.toLowerCase() + "").indexOf(prefix.toLowerCase()) === 0;
}
return function(items, state) {
var filtered = [];
angular.forEach(items, function(item) {
if (strStartsWith(item.state, state)) {
filtered.push(item);
}
});
return filtered;
};
});
Html:
<body ng-app='stateManagement' ng-controller='myCtrl'>
<div class="col-md-12">
<table class="table table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
</tr>
<tr>
<th><input class="form-control"
type="text"
placeholder="Search..."
ng-model="search.Name"/>
</th>
<th><input class="form-control"
type="text"
placeholder="Search..."
ng-model="search.Country"/>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in names | filter:search">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-12">
<input ng-model="state">
<table id="hotels">
<tr data-ng-repeat="element in elements | myfilter:state">
<td>{{element.state}}</td>
</tr>
</table>
<br/>
</div>
</body>
Thank you in advance for helping!

Angular: ng-repeat displaying order in a table

I have an specific requirement where the json data comes like this:
[{Id : "a", Name : "John", age : 50},
{Id : "b", Name : "Bob", age : 40}]
I want to show it in a table using ng-repeat, but in a way where headers come in the first column, as below:
<table>
<tr>
<td>Id</td>
<td>a</td>
<td>b</td>
</tr>
<tr>
<td>Name</td>
<td>John</td>
<td>Bob</td>
</tr>
<tr>
<td>Age</td>
<td>50</td>
<td>40</td>
</tr>
</table>
Is there a way to achieve this using angularjs?
Thanks
Provided you have a controller:
angular.module('MyApp', [])
.controller('MyController', function($scope) {
$scope.data = [
{Id : "a", Name : "John", age : 50},
{Id : "b", Name : "Bob", age : 40}
];
});
Your markup would then be as follows. If the data isn't going to change after it is displayed:
<table>
<tr>
<td>Id</td>
<td ng-repeat="item in ::data">{{::item.Id}}</td>
</tr>
<tr>
<td>Name</td>
<td ng-repeat="item in ::data">{{::item.Name}}</td>
</tr>
<tr>
<td>Age</td>
<td ng-repeat="item in ::data">{{::item.age}}</td>
</tr>
</table>
If the data is going to change after it is displayed, and you want the view to update accordingly, then:
<table>
<tr>
<td>Id</td>
<td ng-repeat="item in data track by $index">{{item.Id}}</td>
</tr>
<tr>
<td>Name</td>
<td ng-repeat="item in data track by $index">{{item.Name}}</td>
</tr>
<tr>
<td>Age</td>
<td ng-repeat="item in data track by $index">{{item.age}}</td>
</tr>
</table>
You can convert your array in an object, then you can use nested ng-repeats in view, as below:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
var array = [
{
"Id":"a",
"Name":"John",
"age":50
},
{
"Id":"b",
"Name":"Bob",
"age":40
}
];
// If you're sure that the properties are always these:
$scope.mainObj = {
"Id": [],
"Name": [],
"age": []
};
// If you're unsure what are the properties:
/*
$scope.mainObj = {};
Object.keys(array[0]).forEach(function(value) {
$scope.mainObj[value] = [];
});
*/
// Iterates over its properties and fills the arrays
Object.keys($scope.mainObj).forEach(function(key) {
array.map(function(value) {
$scope.mainObj[key].push(value[key]);
})
});
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<table>
<tr ng-repeat="(key, values) in mainObj track by $index">
<td ng-bind="key"></td>
<td ng-repeat="value in values track by $index" ng-bind="value"></td>
</tr>
</table>
</body>
</html>
I hope it helps!

triggering all the checkbox event while selecting checkall in angularjs

<table class="table">
<thead>
<th> <input type='checkbox' name='selectall' ng-model="value1" ng-click="selectAll()"></th>
<th> Name </th>
</thead>
<tr ng-repeat="x in items">
<td><input type='checkbox' ng-model="value2" ng-true-value="YES" ng-false-value="NO" ng-click="select($event,x.id)"
/></td>
<td>{{x.name}}</td>
</tr>
</tr>
</table>
How to I get all the item.id when I click "selectall()" checkbox ?
Also, Can you suggest me appropriate ng-model syntax for ng-repeat checkbox ?
Thanks,
Raja K
Take a look at this example, you can see how the checkbox values change,
while using checkbox use ng-change instead of ng-click
// the main (app) module
var myApp = angular.module("myApp", []);
// add a controller
myApp.controller("myCtrl", function($scope) {
$scope.value1 = "NO";
$scope.items = [{
id: 1,
check: "NO",
name: "A"
}, {
id: 2,
check: "NO",
name: "B"
}, {
id: 3,
check: "NO",
name: "C"
}, {
id: 4,
check: "NO",
name: "D"
}, {
id: 5,
check: "NO",
name: "E"
}, {
id: 6,
check: "NO",
name: "F"
}, {
id: 7,
check: "NO",
name: "G"
}, {
id: 8,
check: "NO",
name: "H"
}];
$scope.selectAll = function() {
angular.forEach($scope.items, function(elem) {
elem.check = $scope.value1;
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table class="table">
<thead>
<th>
<input type='checkbox' name='selectall' ng-true-value="YES" ng-false-value="NO" ng-model="value1" ng-change="selectAll()">{{value1}}
</th>
<th>Name</th>
</thead>
<tbody>
<tr ng-repeat="x in items">
<td>
<input type='checkbox' ng-model="x.check" ng-true-value="YES" ng-false-value="NO" ng-change="select($event,x.id)" /> {{x.check}}
</td>
<td>{{x.name}}</td>
</tr>
</tbody>
</table>
</body>
Dear,
Here it's just a helping ref. to your question. I've given a scenario for selecting all records. Hence Modify it according to you need.
<button ng-click="selectAll()">select all</button>
<div ng-repeat="item in items">
<label>
{{item.n}}:
<input type="checkbox" ng-model="selected[item.id]">
</label>
</div>
And in the controller, simply set all the items to be true in selected:
$scope.selected = {};
$scope.selectAll = function(){
for (var i = 0; i < $scope.items.length; i++) {
var item = $scope.items[i];
$scope.selected[item.id] = true;
}
};
Thanks & Cheers
var myapp = angular.module('app', []);
myapp.controller('Ctrl', function ($scope) {
var vm = this;
vm.data = {
items: [
{id:1,name:"ali",selected: "NO"},
{id:2,name:"reza",selected: "NO"},
{id:3,name:"amir",selected: "NO"}
]
};
vm.value1 = false;
vm.selectAll = function($event){
var checkbox = $event.target;
var selected = "NO";
if(checkbox.checked)
{
selected = "YES";
}
else {
selected = "NO";
}
angular.forEach(vm.data.items, function(item) {
item.selected = selected;
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="Ctrl as vm">
<table class="table">
<thead>
<th> <input type='checkbox' name='selectall' ng-model="value1" ng-click="vm.selectAll($event)"></th>
<th> All </th>
</thead>
<tr ng-repeat="x in vm.data.items">
<td><input type='checkbox' ng-model="vm.data.items[$index].selected" ng-true-value="YES" ng-false-value="NO" ng-click="vm.select($event,x.id)"
/></td>
<td>{{x.name}}</td>
</tr>
</table>
</div>

AngularJS search with multiple textboxes

I want to do a search of a table with multiple textboxes. The user should be able to enter address in the address box and search the table my address, and enter city in the city search box and search the table by city. I can't get it to work, I'm getting the error message: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Here's my html:
<table>
<thead>
<tr>
<th>
Address
</th>
<th>
City
</th>
</tr>
<tr>
<td>
<input ng-model="vm.search_address" />
</td>
<td>
<input ng-model="vm.search_city" />
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="search in searchesFound = ( vm.searches | filter: {address: search_address, city: search_city})">
<td>
{{ search.address }}
</td>
<td>
{{ search.city }}
</td>
</tr>
</tbody>
</table>
ANd here's my controller:
(function () {
angular.module('crm.ma')
.controller('AdvancedSearchCtrl', function () {
var vm = this;
vm.search_address = "";
vm.search_city = "";
vm.searchs = [
{
address: '202 This St',
city : 'Columbus'
},
{
address: '205 That St',
city: 'Dayton'
}
]
});
})();
Any clues on what I'm doing wrong?
You forgot the vm object. In your filter vm.search_city and vm.search_address should be used:
<tr ng-repeat="search in vm.searchs | filter: {address: vm.search_address, city: vm.search_city}">
Look this:
var app = angular.module('ngApp', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.smartphones = [
{brand: 'Apple', model: 'iPhone 4S', price: '999'},
{brand: 'Samsung', model: 'SIII', price: '888' },
{brand: 'LG', model: 'Optimus', price: '777'},
{brand: 'htc', model: 'Desire', price: '666'},
{brand: 'Nokia', model: 'N9', price: '555'}
];
$scope.search = function(){
angular.forEach($scope.smartphones, function(value, key) {
var brand = ($scope.queryBrand? $scope.queryBrand.toLowerCase():' ');
var model = ($scope.queryModel? $scope.queryModel.toLowerCase():' ');
value.show = (value.brand.toLowerCase().indexOf(brand) > -1 ||
value.model.toLowerCase().indexOf(model) > -1 || (brand == ' ' && model == ' '));
console.log(!brand && !model)
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.0/css/bootstrap-combined.min.css" rel="stylesheet">
<div ng-app="ngApp" ng-controller="MainCtrl" class="container">
<input class="span4 pull-right" type="text" placeholder="Filter by brand" ng-model="queryBrand" ng-change="search()">
<input class="span4 pull-right" type="text" placeholder="Filter by model" ng-model="queryModel" ng-change="search()">
<div class="row">
<table id="results" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Brand</th>
<th>Model</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="smartphone in smartphones" ng-init="smartphone.show=true" ng-show="smartphone.show">
<td id="brand">{{smartphone.brand}}</td>
<td id="model">{{smartphone.model}}</td>
<td id="price">{{smartphone.price | currency}}</td>
</tr>
</tbody>
</table>
</div>
</div>

Resources