get which are checked in list of checkboxes AngularJS - javascript

I would like to get which checkbox are selected by the user, i have this table but it dosen't work. is there any alternative ?
<table class="table table-bordered table-hover" style="max-height: 500px; overflow-y: auto" border="1">
<tr>
<th> Nom Exigence</th>
<th> Verifier</th>
</tr>
<tr data-ng-repeat="item in list" style="background-color: #F5F5F5">
<td>
{{item.Nom}}
</td>
<td>
<input type="checkbox" checklist-model="user.list" />
</td>
</tr>
</table>
verify
Close
when i try to log the $scoepe.user.list it shows me []
this is the modal controller
app.controller('ModalInstanceExigencesCtrl', function ($scope, $modalInstance, list) {
$scope.list = [];
$scope.user = [];
for (var i = 0; i < list.length; i++) {
$scope.list.push(list[i]);
}
console.log($scope.list);
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
$scope.verify = function () {
console.log($scope.user);
};
});

this Fiddle should do the job for u: jsfiddle example using checkboxes
Html-Code (pretty similiar to ur code):
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
<label class="checkbox">
<input type="checkbox" ng-model="items[$index].checked" />
{{item.name}}
</label>
</li>
</ul>
<hr class="space clearfix" />
{{items | json}}
JS-Code:
var app = angular.module('angularjs-starter', []);
function MainCtrl( $scope )
{
$scope.items = [
{ name:'foo', checked: true },
{ name:'bar' },
{ name:'baz' }
];
}
I just define one $scope Object called items. In my example each item has a name and optional a value checked, which determines wether a checkbox is checked or not.
Html is pretty forward, we repeat over all items and then bind our checkbox model ng-model="items[$index].checked". $index gives us the number of iteration, for example our first iteration binds to ng-model="items[0].checked"
Hope that helps.

You can try by using this way also
Html-Code:
$scope.collectNumbers = function (contact, index) {
if (contact.IsChecked) {
}
else{
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<tr class="" ng-repeat="contact in Contacts">
<td>
<label>
<input type="checkbox" ng-model="contact.IsChecked" ng-change="collectNumbers(contact,$index)" ng-checked="contact.IsChecked">
</label>
</td>
<td>{{contact.Name}}</a></td>
</tr>

Related

how to get all data using select all checkbox in table?

Hi I am trying to get all data at a time when I will click on
checkbox, but data not coming but when i click one by one data id
coming. But my problem is how to get all data in checkbox all in
single click.
This is HTML code
<div id="wrapper" class="wrapper">
<div ng-include="'views/partials/navigator.html'"></div>
<div class="page-content-wrapper">
<div ng-include="'views/partials/header.html'"></div>
<div class="row">
<div class="col-md-12">
<h3>Student Information</h3>
<table id="example" class="table">
<tr>
<th>Name</th>
<th>Mobile</th>
<th>Siblling</th>
<th>select all <input type="checkbox" id="slctAllDuplicateStd"/></th>
</tr>
<tr ng-repeat="data in vm.data">
<td>{{data.name}}</td>
<td>{{data.mobileNumber}}</td>
<td>{{data.isMigrated}}</td>
<td><input type="checkbox" ng-model="data.selected" class="duplicateRow" /></td>
</tr>
<tr>
<tr>
<button class ="button" ng-click="vm.process()">Process</button>
</tr>
</table>
<table class="table">
<tr>
<td colspan="4">
<pagination ng-if="renderpagination" page-number='{{vm.pageNumber}}' page-count="{{vm.pageCount}}" total-records="{{vm.totalRecords}}" api-url="duplicate-student"></pagination>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
This is javascript code
(function() {
angular
.module('vidyartha-coordinator')
.controller('StudentDuplicateAccountController', StudentDuplicateAccountController);
StudentDuplicateAccountController.$inject = ['$scope', 'ApiService', '$routeParams', '$http', '$location', '$timeout'];
function StudentDuplicateAccountController($scope, ApiService, $routeParams, $http, $location, $timeout) {
var vm = this;
//console.log($routeParams)
var page = $routeParams.page || 1;
// vm.data = [];
ApiService.getAll('student-duplicate-account?pageCount=5&pageNumber=' + page).then(function(response) {
//console.log("response::"+JSON.stringify(response));
vm.data = response.data.records;
vm.pageNumber = response.data.pageNumber;
vm.totalRecords = response.data.totalRecords;
vm.pageCount = response.data.pageCount;
$scope.renderpagination = true;
});
$("#slctAllDuplicateStd").click(function () {
$(".duplicateRow").prop('checked', $(this).prop('checked'));
// console.log('data:::'+JSON.stringify(data));
});
vm.process = function() {
vm.duplicateArray = [];
angular.forEach(vm.data, function(data){
if (data.selected) {
console.log("true")
vm.duplicateArray.push(data.tenantId);
vm.duplicateArray.push(data.mobileNumber);
vm.duplicateArray.push(data.schoolId);
vm.duplicateArray.push(data.classId);
}
});
console.log(vm.duplicateArray)
}
}
})();
I need all data at a time we i do check and press process button.
So please tell me where i should add some condition.
Am not sure why you are mixing jquery here you can do it as follow
vm.selectAll =function(){
angular.forEach(vm.data, function(data){
data.selected=true;
}
then in your checkbox
<th>select all <input type="checkbox" ng-click="vm.selectAll()"/></th>

How can I change the innerHTML of div with a variable, inside the scope function in angular js?

I have 2 HTML pages. In my index.html page you can see products information that comes from JSON file. I need to have detail of product in detail.html page when people click on particular product. Alert can show the details but unfortunately the innerHTML of my <p> does not change, please guide me.
<div ng-app="myApp" ng-controller="AppController">
<div id="serachWrapper">
<h1 id="headerTopic">Our Products</h1>
<input id="searchInput" name="search" type="text" placeholder="Search products" ng-model="searchquery"/>
<table id="searchTable">
<thead id="tbHead">
<tr class="tbRow">
<th class="tbTopics">ID</th>
<th class="tbTopics">Name</th>
<th class="tbTopics">Color</th>
<th class="tbTopics">Type</th>
<th class="tbTopics">Capacity</th>
<th class="tbTopics">Price</th>
</tr>
</thead>
<tbody id="tbBody">
<tr class="tbRow" ng-repeat="x in myData | filter:searchquery ">
<td class="tbcontents" >{{x.id}}</td>
<td class="tbcontents">{{x.name}}</td>
<td class="tbcontents">{{x.color}}</td>
<td class="tbcontents">{{x.type}}</td>
<td class="tbcontents">{{x.capacity}}</td>
<td class="tbcontents">{{x.price}}</td>
</tr>
</tbody>
</table>
</div>
And this is my Angular js code:
var app = angular.module('myApp', ['ngSanitize']);
app.controller('AppController', AppController);
function AppController($scope , $http) {
$http.get("products.json").success(function(myData){
$scope.myData = myData;
$scope.go = function(item){
var detail = item.detail;
var productDetail = angular.element(document.getElementById('product-detail')).html();
productDetail = detail;
alert(detail)
};
});
}
You can keep both codes in the page and to solve this with an ng-if directive
Angular ng-if directive
<body ng-app="ngAnimate">
<label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
This is removed when the checkbox is unchecked.
</span>
</body>
Why is your $scope.go function defined inside the http.get request?
Try:
function AppController($scope , $http) {
$http.get("products.json").success(function(myData){
$scope.myData = myData;
});
$scope.go = function(item) {
var detail = item.detail;
var productDetail = angular.element(document.getElementById('product-detail')).html();
productDetail = detail;
alert(detail)
};
}

How to make dynamic content-editable table using angular JS?

Caveat: I've just started with client side scripting and Angular JS is the first thing I'm learning and now I feel I should've started with javascript.
PS: I don't wanna use any third party libraries. I wanna learn to code.
Anyway,I have dynamic table which I want to make editable using content-editable=true attribute of HTML.
Problem: How to I get the edited data? whenever I click on submit and pass the this object to the check() function. I doesn't contain edited values. is there a possible way to pass only edited value if it's dirty. It has pagination so If g to the next page the edited values are gone. I know I've give unique Id to every td element with $Index concatenated to it. But I don't know how should I proceed.
Any help or guidance will be appreciated. Controllers and others are defined in my route.
<div>
<form ng-submit="check(this)">
<table class="table table-striped table-hover">
<tbody>
<tr ng-repeat="data in currentItems">
<td contenteditable="true >{{data.EmpNo}}</td>
<td contenteditable="true">{{data.isActive}}</td>
<td contenteditable="true">{{data.balance}}</td>
<td contenteditable="true">{{data.age}}</td>
<td contenteditable="true">{{data.eyeColor}}</td>
<td contenteditable="true">{{data.fname}}</td>
</tr>
</tbody>
<tfoot>
<td>
<div class="pagination pull-right">
<li ng-class="{'disabled': previousPage}">
<a ng-click="previousPage()" >Previous</a>
</li>
<li ng-repeat="page in pageLengthArray track by $index">
<a ng-click="pagination($index)">{{$index+1}} </a>
</li>
<li disabled="disabled">
<a ng-click="nextPage()" ng-class="{'disabled':nextPage}>Next </a>
</li>
</div>
</td>
</tfoot>
</table>
<input type="submit" value="Submit">
</form>
$scope.currentPage=0;
$scope.pageSize=10;
$scope.currentItems;
$scope.tableData;
$http.get('../json/generated.json').then(function(response){
$scope.tableData=response.data;
$scope.pageLength=Math.ceil($scope.tableData.length/$scope.pageSize);
$scope.currentItems=$scope.tableData.slice($scope.currentPage,$scope.pageSize);
$scope.pageLengthArray= new Array($scope.pageLength);
});
$scope.pagination=function(currentPage){ $scope.currentItems=$scope.tableData.slice($scope.pageSize*currentPage,$scope.pageSize*currentPage+$scope.pageSize);
$scope.currentPage=currentPage;
}
$scope.nextPage=function nextPage(argument) {
$scope.currentPage++; $scope.currentItems=$scope.tableData.slice(($scope.pageSize*$scope.currentPage),($scope.pageSize*($scope.currentPage)+$scope.pageSize));
}
$scope.previousPage=function previousPage(argument) {
$scope.currentPage--;
$scope.currentItems=$scope.tableData.slice(($scope.pageSize*$scope.currentPage),($scope.pageSize*($scope.currentPage)+$scope.pageSize));
}
In the usual case, you can not get a change model for contenteditabe because to change the model used ngModel.
But we can create a directive that we have updated the value of the model.
Live example on jsfiddle.
angular.module('ExampleApp', [])
.controller('ExampleController', function($scope, $timeout) {
$scope.data = {
EmpNo: "123"
};
})
.directive('contenteditable', function($timeout) {
return {
restrict: "A",
priority: 1000,
scope: {
ngModel: "="
},
link: function(scope, element) {
element.html(scope.ngModel);
element.on('focus blur keyup paste input', function() {
scope.ngModel = element.text();
scope.$apply();
return element;
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
<div ng-controller="ExampleController">
<table>
<tr>
<td ng-model="data.EmpNo" contenteditable="true"></td>
</tr>
</table>
<pre>{{data|json}}</pre>
</div>
</div>
I would store any object that gets modified in a seperate array using the ng-keyup directive. When the form is submitted, you will have an array of only elements which have been modified. You may have some UX issues if your pagination is done by server as when you change page and come back, it will show your old data, but hopefully this helps.
$scope.check = function () {
// check modifiedItems
console.log(modifiedItems);
};
// store modified objects in a seperate array
var modifiedItems = [];
$scope.modifyItem = function (data) {
// check if data has already been modified and splice it first
for(var i = 0, j = modifiedItems.length; i < j; i++) {
var currentItem = modifiedItems[i];
if (currentItem.id === data.id) {
modifiedItems.splice(i, 1);
break;
}
}
// add to modified
modifiedItems.push(data);
console.log('modifiedItems: ', modifiedItems);
};
HTML
<form ng-submit="check()">
<table class="table table-striped table-hover">
<tbody>
<tr ng-repeat="data in currentItems">
<td ng-repeat="(key, value) in data" contenteditable="true"
ng-keyup="modifyItem(data)">
{{data[key]}}
</td>
</tr>
</tbody>
<tfoot>
</table>
<input type="submit" value="Submit">
</form>

Highlight filtered rows in Angular JS

I have a array that needs to highlight duplicate values. This is what I have so far..
HTML
<tr ng-repeat="x in names | unique: 'names'" >
<td> {{ x }} </td>
</tr>
<style>
.duplicate{
background: yellow;
}
</style>
Controller:
angular.module('myApp', []).controller('nameCtrl', function($scope) {
$scope.names = [
'Bob',
'Dan',
'Philip',
'Philip',
];
});
EDIT: In the example above "Philip" would be highlighted and would have duplicate class
You can achieve it like this:
<div ng-app="MyApp">
<div ng-controller="MyController">
<table>
<tr ng-repeat="name in names | unique">
<td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
</tr>
</table>
</div>
</div>
This applies the duplicate class for elements where the indexOf returns a different value than the lastIndexOf. This can only happen for items that are in the array more than once.
JSFiddle available here.
If you don't want to filter out the duplicates, you can use this:
<div ng-app="MyApp">
<div ng-controller="MyController">
<table>
<tr ng-repeat="name in names track by $index">
<td ng-class="{ 'duplicate': names.indexOf(name) !== names.lastIndexOf(name) }">{{name}}</td>
</tr>
</table>
</div>
</div>
I think this should work.
<tr ng-repeat="(key, count) in names | count" >
<td ng-class="{your-highlight-class: count > 1 }"> {{ key }} </td>
</tr>
app.filter('count', function ( ) {
return function (collection) {
var result = {};
collection.forEach( function( elm ) {
if(!result[elm]) {
result[elm] = 0;
}
result[elm]++;
});
return result;
}
}]);

Ng-repeat over localStorage data

This is my partial view
<table class="table table-hover" ng-controller="emailViewController">
<tbody>
<tr >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td><label ng-bind="add"></label></td>
<td><label ng-bind="subject"></label></td>
<td><label ng-bind="emailContent" ></label></td>
</tr>
</tbody>
</table>
I have this data stored in localStorage:
I want to ng-repeat over the values of the keys ngStorage-add and ngStorage-subject. I tried the following:
1) <td><label ng-bind="add" ng-repeat="item in localStorage.getItem('ngStorage-add')"></label></td>.
2) ng-repeat="item in localStorage.getItem('ngStorage-add') track by value"
It did not work however. Does anyone have ideas on how to achieve this?
EDIT
emailViewController:
(function() {
'use strict';
var emailViewController = function (fetchDataService, $scope,$filter,$timeout, $localStorage) {
$scope.to = [];
var url = 'app/mock/emails.json';
fetchDataService.getContent(url)
.then(function(response){
$scope.emails = response.data;
$scope.loadEmails('Primary');
angular.forEach($scope.emails, function(key) {
$scope.to.push(key.to);
});
});
$scope.information = {
add: [],
subject: [],
emailContent: []
};
$scope.typeaheadOpts = {
minLength: 1
};
$scope.$on("decipher.tags.added", function(info, obj) {
$timeout(function(){
tagAdded(info, obj);
});
});
function tagAdded(info, obj) {
for (var i = 0; i < $scope.to.length; i++) {
if ($scope.to[i] === obj.tag.name) {
$scope.to.splice(i, 1);
}
}
}
$scope.close = function(){
//console.log("hide");
$('.modal').modal('hide');
};
$scope.loadEmails = function(searchCriteria){
$scope.filteredEmails = $filter('filterByCategory')
($scope.emails,searchCriteria);
};
$scope.submit = function (add, subject, emailContent) {
if (! ($localStorage.add instanceof Array) ) {
$localStorage.add = [];
}
$localStorage.add.push(add);
if (! ($localStorage.subject instanceof Array) ) {
$localStorage.subject = [];
}
$localStorage.subject.push(subject);
if (! ($localStorage.emailContent instanceof Array) ) {
$localStorage.emailContent = [];
}
$localStorage.emailContent.push(emailContent);
//$scope.update();
};
$scope.clear = function() {
$scope.information.add = [];
$scope.information.subject = '';
$scope.information.emailContent = '';
}
$scope.$on('loadEmail',function(event,data){
$scope.loadEmails(data);
});
};
angular.module('iisEmail')
.controller ('emailViewController',
['fetchDataService', '$scope','$filter', '$timeout', '$localStorage', emailViewController]);
}());
ATTEMPT 1
This is returning the array - $localStorage.add
This is returning the first element of the array (a in this case) - $localStorage.add[0][0]
ATTEMPT 2
I injected $localStorage in the directive that was loading the template. It still does not work.
(function() {
'use strict';
var drafts = function ($localStorage) {
return {
templateUrl : "app/partials/draftsView.html"
};
};
angular.module('iisEmail').directive("drafts", ['$localStorage', drafts]);
}());
ATTEMPT 3
I stored the $localStorage data in a controller variable and got ng-repeat to iterate over the variable.
<td><label ng-repeat="item in addition track by $index">
{{item}}
</label></td>
Doing so produces a result, but the entire array is appearing in one line. I want a to be displayed in one line, and b to be displayed in the next line.
ATTEMPT 3 UPDATE
This is the updated partial view
<table class="table table-hover" ng-controller="emailViewController">
<tbody>
<tr >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td><label ng-repeat="item in addition track by $index">
{{item}}
</label></td>
<td><label ng-bind="subject"></label></td>
<td><label ng-bind="emailContent" ></label></td>
</tr>
</tbody>
</table>
ATTEMPT 4
I modified the partial view as follows, and achieved exactly what I was looking for. Now, values of the keys are displayed in new lines. However, they are being displayed like so:
`[a]
[b]
[c]`
I dont want the array symbol to be shown. Here is the modified partial view.
<table class="table table-hover" ng-controller="emailViewController">
<tbody>
<tr ng-repeat = "(key, value) in addition" >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td> {{ value }} </td>
<td><label ng-bind="subject"></label></td>
<td><label ng-bind="emailContent" ></label></td>
</tr>
</tbody>
</table>
SOLUTION
<table class="table table-hover" ng-controller="emailViewController">
<tbody>
<tr ng-repeat = "(key, value) in localStorage.add" >
<td><input type="checkbox" ng-checked="checkAllEmail" ng-model="selectedEmail"/>
<a href="#">
<span class="glyphicon glyphicon-star-empty"></span>
</a></td>
<td ng-repeat = "value in value"> {{value }} </td>
<td><label ng-bind="subject"></label></td>
<td><label ng-bind="emailContent" ></label></td>
</tr>
</tbody>
</table>
LocalStorage can only store string values, i believe you saved the JSON object into local storage by serializing it using JSON.stringify()
so, in order to get the JSON object from localstorage, you can use JSON.parse() function like below,
var add = JSON.parse(localStorage.getItem('ngstorage-add'))
var subject = JSON.parse(localStorage.getItem('ngstorage-subject'))
then you can iterate over it.
Read more about LocalStorage
In order your angular directive should work, you have to make it available to the scope, so you have to do in your controller, something like this:
.controller('Ctrl', function(
$scope,
$localStorage
){
$scope.localStorage = $localStorage;
});

Categories