select all checkboxes with angular JS - html

I am trying to select all checkboxes with one single checkbox. But how to do that?
This is my HTML:
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<!-- userlist -->
<!--<div id="scrollArea" ng-controller="ScrollController">-->
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
I create an extra checkbox to selecet and unselect all checkboxes.
JS:
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = true;
});
};
});
I tried this too, but none of them works for me :(
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = $scope.selectAll;
});
};

You are missed the container divs with ng-controller and ng-app and angular.module.
user.select = $scope.selectAll is the correct variant.
https://jsfiddle.net/0vb4gapj/1/

Try setting the checked boxes against each user to be checked when the top checkbox is checked:
<input type="checkbox" ng-model="selectAll"/>
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select" ng-checked="selectAll"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>

Here is a JSFiddle you can use ng-checked with a variable on it like user.checked (or use the user.select as you want)
<div ng-app="app" ng-controller="dummy">
<table>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>
<input type="checkbox" ng-click="usersetting(user)" ng-checked="user.checked" ng-model="user.select">
</td>
<td><tt>{{user.select}}</tt>
<br/>
</td>
</tr>
</table>
<button ng-click="checkAll()">Check all</button>
</div>
JS:
var app = angular.module("app", []);
app.controller('dummy', function($scope) {
$scope.users = [{
id: 1,
name: "Hello",
select: 1
}, {
id: 2,
name: "World",
select: 1
}, ];
$scope.checkAll = function() {
angular.forEach($scope.users, function(user) {
user.checked = 1;
});
}
});

Simple use the following code
HTML
<input type="checkbox" ng-model="checkboxes.checked" data-ng-click="checkAll()" class="select-all" value="" />
JS
$scope.checkAll = function() {
angular.forEach($scope.users, function(item) {
$scope.checkboxes.items[item._id] = $scope.checkboxes.checked;
$scope.selection.push(item._id);
});
}

Related

Displaying multiple jsons in VUE

So this is my code
<script>
export default {
name: "app",
data() {
return {
items: []
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items = res
return res
}),
this.makeAjaxCall("authors.json", "get").then(resA => {
this.items = resA
return resA
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
</template>
I have the function makeAjaxCall that brings me the books.json, but I want to use it for multiple jsons.
I tried to call it under created, with a different json, authors.json, but it doesn't work.
I guess the syntax is wrong.
I know the function could have been created better, but I would like to keep its initial form or maybe add a parameter to be the json file.(Tried that, but didn't work for me)
Any ideas, pretty please?
To bind the data you have to declare first items: {books:[],authors:[]}
Also you are overwriting this.items use this.items.books and this.items.authors to assign.
Below is the example which works without ajax
new Vue ({
el: "#app",
data() {
return {
items: {books:[],authors:[]}
};
},
created: function() {
this.items.books = this.makeAjaxCall("books", "get");
this.items.authors = this.makeAjaxCall("authors", "get");
},
methods: {
makeAjaxCall:function(url, methodType){
if(url == 'books'){
promiseObj= [{name:'name11',author:'author11',genre:'genre11'},{name:'name12',author:'author12',genre:'genre12'}]
}else{
promiseObj= [{name:'name22',author:'author22',genre:'genre22'}]
}
return promiseObj;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
<table class="authorsTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.authors" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
So I found the answer, after millions of tries and it's pretty simple.
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>

How to get cell value

How to get a cell value from HTML table using ng-click directive?
I need to implement the best way to capture the values of a row using ng-click
Html table:
<div ng-controller="myController">
<table>
<thead>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</thead>
<tbody>
<tr ng-repeat="item in stutents">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td><button type="button" ng-click="getCellValue()">View</button></td>
</tr>
</tbody>
</table>
</div>
My controller:
var app = angular.module('firstApp', []);
app.controller('myController', function($scope){
$scope.stutends = {};
//array values... etc
$scope.getCellValue = function() {
//i want values index, ej. table[0] = id, table[1] = name etc... its posible ?, ej
//var name = table[1]
console.log(name);
}
});
Pass the object as a parameter to the function and access it
<td><button type="button" ng-click="getCellValue(item)">View</button></td>
Controller
$scope.getCellValue = function(item) {
console.log(item.name);
console.log(item.id);
}
var app = angular.module('firstApp', []);
app.controller('myController', function($scope) {
$scope.students = [{
name: 'dat',
id: '00',
age: 12
}];
//array values... etc
$scope.getCellValue = function(item) {
console.log(item.name);
console.log(item.id);
}
});
<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in students">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td><button type="button" ng-click="getCellValue(item)">{{item.id}}</button></td>
</tr>
</tbody>
</table>
</body>
</html>
pass the index to that method by using $index
<td><button type="button" ng-click="getCellValue($index)">View</button></td>
getting from controller
$scope.getCellValue = function(index) {
console.log($scope.stutents[index].name);
console.log($scope.stutents[index].id);
}
And also you can get it from #sachila answer :)
var app = angular.module('firstApp', []);
app.controller('myController', function($scope) {
$scope.students = [{
name: 'A',
id: '1',
age: 12
},{
name: 'B',
id: '2',
age: 10
},
{
name: 'C',
id: '3',
age: 22
}];
//array values... etc
$scope.getCellValue = function(index) {
console.log($scope.students[index].id);
}
});
<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in students">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td><button type="button" ng-click="getCellValue($index)">{{item.id}}</button></td>
</tr>
</tbody>
</table>
</body>
</html>

How to select dropdownlist values of particular text value which is in ng-repeat and ng-model in angularjs and how can we post it to database

I'm pretty new to angularjs.So,please kindly ignore if there are any errors.Here I have one dropdownlist within ng-repeat if I select the values in dropdownlist the corresponding Item code and the selected description from dropdownlist should pass to angularcontroller and I need to post it to the mvc controller
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope',function ($scope, $http,$rootScope) {
$scope.values = [{
Code: 1,
Description: 'Apple'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Mango'
}, {
COde: 4,
Description: 'Guva'
}
];
$scope.ddlrhs = '';
$scope.data = [{
Code: 1,
Description: 'Red'
}, {
Code: 2,
Description: 'Orange'
}, {
Code: 3,
Description: 'Yellow'
}, {
Code: 4,
Description: 'Green'
}
];
$scope.submit = function ()
{
$scope.list = [];
for (var i = 0; i < $scope.values.length; i++) {
var j = "";
$scope.list.push({
VALUE: $scope.values[i].Code,
Description: $scope.myForm.items[i].Description
})
}
$http({
method: "POST",
url: "/Controller/Save",
data:
$scope.list
})
}
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<div id="dvcollection" ng-App="myApp" ng-controller="ctrl" >
<form name="myForm" >
<table id="tblcollections">
<thead>
<tr >
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="myForm.items[$index]" ng-options=" element.Description for element in data ">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()"style="float:right;" >
</td>
</tr>
</tbody>
</table>
</form>
</div>
Hey May be this might be your expectation
<div ng-app="myApp" >
<div id="dvcollection" ng-controller="ctrl">
<form name="myForm">
<table id="tblcollections">
<thead>
<tr>
<th>ItemCode</th>
<th>ItemDesc</th>
<th>DropdownDesc</th>
<th>DropdownCode</th>
<th></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in values">
<td><span>{{item.Code}}</span> </td>
<td>{{item.Description}}</td>
<td>
<select ng-model="itemssample" ng-options=" element.Description for element in data " ng-change="pushingelement(item.Code,itemssample.Code)">
<option value="">Select </option>
</select>
</td>
<td><span>{{myForm.items[$index].Code}}</span></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<input type="button" value="save" ng-click="submit()" style="float:right;">
</td>
</tr>
</tbody>
</table>
</form>
<div> This is written to ensure that mapping is stored or not. (Not necessary)
<p ng-repeat="item in list">
Mapping of {{$index}} element {{item.ItemCode}} -> {{item.ColorCode}}
</p>
</div>
</div>
</div>
Ensure that your MVC Controller should have a model as
public class MapperClass
{
public int ItemCode { get; set; }
public int ColorCode { get; set; }
}
SCRIPT
angular.module('myApp', [])
.controller('ctrl', ['$scope', '$http', '$rootScope', function ($scope, $http, $rootScope) {
$scope.list = [];
$scope.values = [
{ Code: 1, Description: 'Apple' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Mango' },
{ Code: 4, Description: 'Guva' }
];
$scope.ddlrhs = '';
$scope.data = [
{ Code: 1, Description: 'Red' },
{ Code: 2, Description: 'Orange' },
{ Code: 3, Description: 'Yellow' },
{ Code: 4, Description: 'Green' }
];
$scope.pushingelement = function (itemCode, colorCode) {
var temp = { "ItemCode": itemCode, "ColorCode": colorCode };
$scope.list.push(temp);
console.log($scope.list);
}
$scope.submit = function () {
$http({
method: "POST",
url: "/Controller/Save",
data:
object:$scope.list
})
}
}
]);
TRY ONCE I HOPE IT HELPS YOU
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>get selected value from dropdownlist in angularjs</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('sampleapp', [])
app.controller('samplecontrol', function ($scope) {
$scope.sample = [{
id: '1',
name: 'Red'
}, {
id: '2',
name: 'Green'
}, {
id: '3',
name: 'Orange'
}, {
id: '4',
name: 'Yellow'
}];
});
</script>
</head>
<body data-ng-app="sampleapp" data-ng-controller="samplecontrol">
<form id="form1">
Select Name:
<select data-ng-model="ddlvalue">
<option value="">--Select--</option>
<option data-ng-repeat="t in sample" value="">{{t.name}}</option>
</select>
</form>
</body>
</html>

AngularJS custom filter for highlight text

I create a filter on a table. Here the code:
<table id="tableText" class="table table-hover table-striped" ng-init="allNews()">
<tr>
<td colspan="5">
<input type="text" placeholder="Ricerca testo" class="form-control" ng-model="inputText">
</td>
</tr>
<tr>
<th>Titolo</th>
<th>Text</th>
<th>Disattivato</th>
<th>Modifica</th>
<th ng-if="!cancelDelete">Elimina</th>
<th ng-if="cancelDelete">Annulla</th>
</tr>
<tr ng-repeat="news in allNews | filter : inputText">
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteTitle"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.title" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteText"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.arg" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><input type="checkbox" disabled ng-model="news.isDeleted"></div>
<div ng-show="editingData[news.id]"><input type="checkbox" ng-model="news.isDeleted"></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="modify" class="btn btn-primary" ng-click="modify(news, $event)">Modifica</button></div>
<div ng-show="editingData[news.id]"><button id="accept" class="btn btn-success" ng-click="update(news)">Accetta</button></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="delete" class="btn btn-danger" ng-click="delete(news.id)">Cancella</button></div>
<div ng-show="editingData[news.id]"><button id="cancel" class="btn btn-danger" ng-click="cancelModify()">Annulla</button></div>
</td>
</tr>
</table>
The entry on the table is read from db:
$scope.allNews = function () {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
I'd like to highlight the text that is search in the 1st row of the table. For now, i receive this error:
angular.js:13920 Error: [filter:notarray] Expected array but received: function ()
but the filter works.
Your problem is that $scope.allNews is a function. When you use it in ng-repeat directive and the directive is evaluated for the first time, your angular will try to examine the allNews property of your $scope as an array.
When the function gets called the first time (which might never happen when angular first encouters the error), it woul overwrite the allNews property with the resulting array of your $http POST request.
Rename either the function or the property and bind your ng-repeat to the array it recieves (and maybe initialize it with an empty array until it is populated by the $http result).
Something like:
$scope.allNews = [];
$scope.getAllNews = function() {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
Alternatively try using ngResource, create a service and inject that into your controller. Then populate the array by accessing the service.

Editing an item from ng-repeat

So far I've been successful in creating a function that removes an element from ng-repeat and to toggle a form. I can't figure out how to edit a given element in that ng-repeat.
Ideally, I'd like to click on the element, and have the form show with the existing values already in the input. So that all the user needs to do is edit whichever fields desired, click submit and that newly updated item is then added back to the array where it originally was.
This is what I've come up with:
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
<input type="text" />
<input type="text" />
<button ng-click="vm.update()">Submit</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list">
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm()">E</span>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
and:
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function() {
vm.showEditForm = !vm.showEditForm;
};
vm.update = function() {
// ???
}
}
function testSrvc() {
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function() {
this.list.splice() //???
}
}
You need to tell which item you want to edit. So it should be
<span ng-click="vm.edit(item)">E</span>
Then this function should store a copy of that item to edit in some variable:
vm.edit= function(item) {
vm.editedItem = angular.copy(item);
};
And the form should be bound to this item copy:
<input type="text" ng-model="vm.editedItem.name"/>
<input type="text" ng-model="vm.editedItem.desc"/>
Then the save method should find back the original item in the array (thanks to its ID or index), and copy the edited fields from vm.editedItem.
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
this.index1 = -1;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function(item,index) {
this.show = true;
this.index1 = index;
};
vm.update = function(item,index) {
vm.list[index].name = item.name;
vm.list[index].desc = item.desc;
this.index1 = -1;
}
}
function testSrvc() {
this.show = false;
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function(index) {
this.show = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list" >
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm(item,$index)">E</span>
<input ng-show="vm.index1 == $index" type="text" ng-model="item.name" />
<input ng-show="vm.index1 == $index" type="text" ng-model="item.desc" />
<button ng-show="vm.index1 == $index" ng-click="vm.update(item,$index)">Submit</button>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>