Angularjs: Check to push and unchecked to splice id from array - angularjs

I have a table fetched from php script. given below code work perfectly when i tick the box it push ids successfully but while splice it didn't work well.
it splice array too when i tick and untick only single row. but when i select multiple rows it push again and again even when i untick. please check the code.
$scope.exampleArray = [];
$scope.pushInArray = function(id) {
// get the input value
/* var inputVal = id;*/
var index = $scope.exampleArray.indexOf(id);
if( index ){
$scope.exampleArray.push(id);
}else { $scope.exampleArray.splice(index, 1); }
$scope.deleteBulk = function(){
if(confirm("Are you sure you want to delete " + $scope.exampleArray.length + " record(s))?")){
$http.post('http://localhost/angular-code-crud/index.php/user/bulk_delete_user',
{'id':$scope.exampleArray}).success(function(){
$scope.displayUsers();
});
}
};
};
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th></th>
<th ng-click="sort('name')">Name
<span class="glyphicon sort-icon" ng-show="sortKey=='name'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}"></span></th>
<th ng-click="sort('gender')">Gender<span class="glyphicon sort-icon" ng-show="sortKey=='gender'" ng-class="{' glyphicon glyphicon-chevron-up':reverse,' glyphicon glyphicon-chevron-down':!reverse}"></span>
<th ng-click="sort('email')">Email<span class="glyphicon sort-icon" ng-show="sortKey=='email'" ng-class="{' glyphicon glyphicon-chevron-up':reverse,' glyphicon glyphicon-chevron-down':!reverse}"></span></th>
<th>Address</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- <tr ng-repeat="user in users | filter:searchUser | orderBy:sortKey:reverse | filter:paginate"> -->
<tr ng-repeat="user in users|orderBy:sortKey:reverse|filter:searchUser " >
<td><!-- <input type="checkbox" ng-click="deleteBulk(user.id)" ng-true-value="{{user.id}}" ng-checked="master" checklist-model="user.id" checklist-value="{{user.id}}">{{ user.id }} -->
<div class="checkbox">
<label>
<input type="checkbox" name="arrExample" ng-model="arrInput" ng-change='pushInArray(user.id)' >
</label>
</div>
</td>
<td>{{ user.name }}</td>
<td>{{ user.gender }}</td>
<td>{{ user.email }}</td>
<td>{{ user.address }}</td>
<td>{{ user.phone }}</td>
<td>
<button class="btn btn-primary" ng-click="updateData(user.id, user.name, user.gender, user.email, user.address, user.phone)">Edit <i class="material-icons">mode_edit</i></button>
<button class="btn btn-danger" ng-click="deleteData(user.id)">Delete <i class="material-icons">delete</i></button>
</td>
</tr>
</tbody>
</table>
sorry for bad English.

Nevermind i found where was bug.
$scope.exampleArray = [];
$scope.pushInArray = function(id) {
// get the input value
/* var inputVal = id;*/
//$scope.exampleArray.push(id);
var index = $scope.exampleArray.indexOf(id);
console.log(index);
if(index === -1 ){ //this is where i have bug. match the condition with -1
$scope.exampleArray.push(id);
} else { $scope.exampleArray.splice(index, 1);}
$scope.deleteBulk = function(){
if(confirm("Are you sure you want to delete " + $scope.exampleArray.length + " record(s))?")){
$http.post('http://localhost/angular-code-crud/index.php/user/bulk_delete_user',
{'id':$scope.exampleArray}).success(function(){
$scope.displayUsers();
});
}
};
};

Hope this helps
JS :
$scope.pushInArray = function(data) {
var index = $scope.exampleArray.indexOf(data.id);
if(data.checked) {
if( index === -1 ) {
$scope.exampleArray.push(data.id);
}
} else {
$scope.exampleArray.splice(index, 1);
}
}
HTML : change input type="checkbox" line to below
<input type="checkbox" name="arrExample" ng-model="user.checked" ng-change='pushInArray(user)' >

change condition index
$scope.pushInArray = function (id) {
var index = $scope.exampleArray.indexOf(id);
if (index <= -1) {
$scope.exampleArray.push(id);
} else
$scope.exampleArray.splice(index, 1);
};
};

Related

How to Sum From Multi object

Please help me, I'm using 2 JSON feed, need to display array value in one table then add sum row for each column, but I don't know how to call Expense Table and sum it.
Income JSON Table:
nominal_income
Expense JSON Table:
nominal_expense
If you have any example please let me know :D
My HTML:
<table ng-controller="incomeCtrl">
<tr>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="item in incomes" ng-init="$last ? runEvent(item) : null">
<td class="text-left">{{item.nominal_income}}</td>
<td class="text-left">{{item.nominal_expense}}</td> // how to call this?
</tr>
<tr>
<td class="text-left" >{{ income_total | number:2 }}</td>
<td class="text-left" >{{ expense_total | number:2 }}</td> //how to sum this ?
</tr>
</table>
JS Controller:
$scope.runEvent = function(item) {
var income_total = 0;
angular.forEach(item, function(item) {
income_total = income_total -(- incomes.nominal_income)
;})
$scope.income_total = income_total;}
Use a custom function and call the function with key parameter
angular.module("test",[]).controller("testc",function($scope) {
$scope.incomes=[{nominal_income:20,nominal_expense:75.5},{nominal_income:30.00,nominal_expense:14.50},{nominal_income:49.99,nominal_expense:10}]
$scope.average = function(array, key) {
var value= 0,
average;
for (var i = 0; i < array.length; i++) {
value+= array[i][key];
}
return value;
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="test" ng-controller="testc">
<table >
<tr>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="item in incomes" ng-init="$last ? runEvent(item) : null">
<td class="text-left">{{item.nominal_income}}</td>
<td class="text-left">{{item.nominal_expense}}</td>
</tr>
<tr>
<td style="color:green" class="text-left" >{{average(incomes,"nominal_income") | number:2 }}
</td>
<td style="color:green" class="text-left" >{{average(incomes,"nominal_expense") | number:2 }}
</td>
</tr>
</table>
</div>
Update: How to join IncomeCtrl and ExpenseCtrl
You can call another controller inside a controller as nested controller. Or you can pass the data from one controller to another controller by using $routScope or $Cookies or $service or $BroadCase etc
<table ng-controller="incomeCtrl">
<tr>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="item in incomes" ng-init="$last ? runEvent(item) : null">
<td class="text-left">{{item.nominal_income}}</td>
<td ng-controller="ExpenseCtrl" class="text-left">{{expenses[$index].nominal_expense}}</td> // may you need $$parent.$index
</tr>
<tr>
<td style="color:green" class="text-left" >{{average(incomes,"nominal_income") | number:2 }}
</td>
<td ng-controller="ExpenseCtrl" style="color:green" class="text-left" >{{average(expenses,"nominal_expense") | number:2 }}
</td>
</tr>
</table>
You can pass a type / column as a parameter to be reduced to get the sum. Here is an example:
var app = angular.module('myApp', []);
app.controller('incomeCtrl', function($scope, incomeService) { // incomeService injected here as a serivce
var inc = incomeService.get_income();
var exp = incomeService.get_expense();
$scope.incomes = [];
/* works if `inc` and `exp` have the same length, merge with caution! */
for (var i = 0; i < inc.length; i++) {
$scope.incomes.push({
"nominal_income": inc[i],
"nominal_expense": exp[i]
})
}
$scope.sum = function(type) {
return $scope.incomes.reduce((x, y) => {
return x + y[type];
}, 0);
}
});
app.factory('incomeService', function() {
var service = {};
var data = {
"income": [2.01, 3.23, 6.56],
"expense": [1.12, 2.34, 5.67]
}
service.get_income = function() {
return data.income;
}
service.get_expense = function() {
return data.expense;
}
service.set_income = function(array) { // populated in incomeCtrl
data.income = array;
}
service.set_expense = function(array) { // populated in expenseCtrl
data.expense = array;
}
return service;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myApp" ng-controller="incomeCtrl">
<table>
<tr>
<td>Income</td>
<td>Expense</td>
</tr>
<tr ng-repeat="item in incomes">
<td class="text-left">{{item.nominal_income}}</td>
<td class="text-left">{{item.nominal_expense}}</td>
</tr>
<tr style="color:red;">
<td class="text-left">{{sum('nominal_income') | number:2}}</td>
<td class="text-left">{{sum('nominal_expense') | number:2}}</td>
</tr>
</table>
</div>

Search filter not working for full list of lazy loading pagination using Angularjs

I have a table list and loading lazily with pagination - only 5 items at a time. Sorting & pagination working fine,even search also working but only current page. Total list size is 788, When the user clicks the next page another 5 are loaded etc. However I also want to have an option of searching for an item within the full list - not the lazy list.
MY HTML:
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12" ba-panel ba-panel-title="Requirement Details" ba-panel-class="with-scroll" >
<form class="form-inline">
<div class="form-group">
<input type="text" ng-model="search" class="form-control" placeholder="Search">
</div>
</form>
<div class="horizontal-scroll">
<div ng-init="reqTableData(1)"> </div>
<table class="table" >
<thead>
<tr class="sortable ">
<th style="width:5%" ng-click="sort('reqID',1)"> ID
<span class="glyphicon sort-icon" ng-show="sortBy=='reqID'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:15%" ng-click="sort('reqName',1)">Name
<span class="glyphicon sort-icon" ng-show="sortBy=='reqName'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:20%" ng-click="sort('description',1)">Description
<span class="glyphicon sort-icon" ng-show="sortBy=='description'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:10%" ng-click="sort('reqType',1)">Type
<span class="glyphicon sort-icon" ng-show="sortBy=='reqType'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:15%" ng-click="sort('creationTime',1)">Created On
<span class="glyphicon sort-icon" ng-show="sortBy=='creationTime'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:20%" ng-click="sort('status',1)">Status
<span class="glyphicon sort-icon" ng-show="sortBy=='status'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:15%" ng-click="sort('priority',1)">Priority
<span class="glyphicon sort-icon" ng-show="sortBy=='priority'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
<th style="width:15%" ng-click="sort('lastModified',1)">Modified On
<span class="glyphicon sort-icon" ng-show="sortBy=='lastModified'" ng-class="{'glyphicon-chevron-up':reverse,'glyphicon-chevron-down':!reverse}">
</span>
</th>
</tr>
</thead>
<tbody >
<tr dir-paginate="item in reqTableDetails|orderBy:sortBy:reverse|filter:search|itemsPerPage: 5" total-items="reqdata">
<td style="width:5%">{{item.reqID}}</td>
<td style="width:15%" class="trim-info" title="{{item.reqName}}">{{item.reqName|limitTo:10}}{{item.reqName.length>10 ? '...' : ''}}</td>
<td style="width:20%" class="trim-info" title="{{item.description}}">{{item.description|limitTo:25}}{{item.description.length>25 ? '...' : ''}}</td>
<td style="width:10%">{{item.reqType}}</td>
<td style="width:15%">{{item.creationTime | date:'MM/dd/yyyy'}}</td>
<td style="width:20%">{{item.status}}</td>
<td style="width:15%">{{item.priority}}</td>
<td style="width:15%">{{item.lastModified | date:'MM/dd/yyyy'}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls directions-links="true"
boundary-links="true"
on-page-change="reqpageChangedLevel(newPageNumber)"></dir-pagination-controls>
</div>
</div>
</div>
Controller.js
$scope.reqpageChangedLevel=function(pageno){
$rootScope.pageno = pageno;
if($rootScope.domain == null || $rootScope.domain == null || $rootScope.domain == ""){
{
if( $scope.sortBy=="")
{
$scope.reqTableData ($rootScope.pageno) ;
}else
{
$scope.sortedtable($scope.sortBy,$rootScope.pageno,$scope.reverse);
}
}
}
else
{
$scope.level1 = $rootScope.domain ;
$scope.level2 = $rootScope.project ;
$scope.level3 = $rootScope.release ;
if( $scope.sortBy=="")
{
$scope.reqtabledataLevel($scope.level1,$scope.level2,$scope.level3,$rootScope.pageno);
}else
{
$scope.sortedtableLevel($scope.level1,$scope.level2,$scope.level3,$scope.sortBy,$rootScope.pageno,$scope.reverse);
}
}
};
var vm = this;
vm.total_count = 0;
$scope.itemsPerPage = 5;
// Table on-load
$scope.reqTableData = function(start_index){
$scope.index=start_index;
$http.get("./rest/requirementServices/reqTableDetails?&itemsPerPage="+$scope.itemsPerPage+"&start_index="+$scope.index).success(function (response) {
$scope.reqTableDetails = response;
}) ;
};
// Table on drop down change with level id
$scope.reqtabledataLevel = function(level1,level2,level3,start_index){
$scope.index = start_index;
$scope.smartTablePageSize = 5;
$http.get("./rest/requirementServices/reqTableDetailsLevel?level1="+level1+"&level2="+level2+"&level3="+level3+"&itemsPerPage="+$scope.itemsPerPage+"&start_index="+$scope.index).success(function (response) {
$scope.reqTableDetails = response;
}) ;
}
// Sort function starts here
$scope.sort = function(keyname,start_index){
$scope.sortBy = keyname;
$scope.index=start_index;
$scope.reverse = !$scope.reverse;
if($rootScope.domain == null || $rootScope.domain == null || $rootScope.domain == ""){
$scope.sortedtable ($scope.sortBy,$scope.index,$scope.reverse) ;
}
else
{
$scope.level1 = $rootScope.domain ;
$scope.level2 = $rootScope.project ;
$scope.level3 = $rootScope.release ;
$scope.sortedtableLevel($scope.level1,$scope.level2,$scope.level3,$scope.sortBy,$scope.index,$scope.reverse);
}
};
//Table on-load with sort implementation
$scope.sortedtable =function(sortvalue,start_index,reverse)
{
$scope.column=sortvalue;
$scope.index=start_index;
$scope.order=reverse;
$http.get("./rest/requirementServices/requirementsData?sortvalue="+$scope.column+"&itemsPerPage="+$scope.itemsPerPage+"&start_index="+$scope.index+"&reverse="+$scope.order).success(function (response) {
$scope.reqTableDetails = response;
}) ;
}
// Table on drop down change with sort implementation
$scope.sortedtableLevel =function(level1,level2,level3,sortvalue,start_index,reverse)
{
$scope.column=sortvalue;
$scope.index=start_index;
$scope.order=reverse;
$http.get("./rest/requirementServices/requirementsDataLevel?sortvalue="+$scope.column+"&itemsPerPage="+$scope.itemsPerPage+"&start_index="+$scope.index+"&reverse="+$scope.order+"&level1="+$scope.level1+"&level2="+$scope.level2+"&level3="+$scope.level3).success(function (response) {
$scope.reqTableDetails = response;
}) ;
}
/* Lazy Load Table Ends Here */
I've tried with code in controller.js but its not working, so that i removed.
How can i keep my list displayed lazily but have the search box filter items from my full list.
I'm figuring out the same issue. To properly test I tried to load elements either in single call or lazy load. In case of lazy loading $filter doesn't work.

How to delete object from table in angular factory using underscore.js?

<!--customers view-->
<div class="container">
<div class="row">
<div class="col-md-12">
<table class="table table-responsive table-striped">
<tr>
<th ng-click="doSort('name')">Name</th>
<th ng-click="doSort('city')">City</th>
<th ng-click="doSort('order')">OrderTotal</th>
<th ng-click="doSort('joined')">Join</th>
<th>Orders</th>
<th>Delete</th>
</tr>
<tr ng-repeat="cust in customers |filter:customerFilter | orderBy:sortBy:reverse" class="repeat-animation">
<td>{{ cust.name | uppercase }}</td>
<td>{{ cust.city }}</td>
<td>{{ cust.orderTotal | currency: 'AED ' }}</td>
<td>{{ cust.joined | date}}</td>
<td>View Orders</td>
<td class="center"><span class="glyphicon glyphicon-remove delete" ng-click="remove(cust.id)"></span></td>
</tr>
</table>
</div>
</div>
</div>
/*------------Customer Controller-------------------*/
myApp.controller('CustomersController', ['$scope', 'customersFactory', 'appSettings', function($scope, customersFactory, appSettings) {
var customers = [];
$scope.sortBy = 'name';
$scope.reverse = false;
$scope.appSettings = appSettings;
function init() {
$scope.customers = customersFactory.getCustomers();
}
init();
$scope.doSort = function(propName) {
$scope.sortBy = propName;
$scope.reverse = !$scope.reverse;
}
$scope.remove = function(customer) {
customersFactory.remove(customer);
};
}]);
/* factory remove method*/
factory.remove = function(item) {
factory.customers = _.reject(factory.customers, function(element) {
return element.id === item.id;
});
};
return factory;
I am making table which display the customers and their order and I want to delete the particular orders with the help of underscore reject method, but it is not deleting. My angular version is 1.5. Can anyone suggest the solution?

I can't seems to edit a field in angular js

I have this edit form on my index.html
<tbody>
<tr ng-repeat="client in vm.clients | orderBy: '-ClientID'" ng-dblclick="vm.clickEditAction(client)">
<td><img src="/img/trash.png" style="cursor: pointer;" ng-click="vm.removeAction(client)" alt="Remove {{ client.ClientID }}" /></td>
<td>{{ client.ClientID }}</td>
<td>
<span data-ng-hide="editMode">{{ client.ClientName }}</span>
<input type="text" data-ng-show="editMode" data-ng-model="client.ClientName" data-ng-required />
</td>
<td>{{ client.Country }}</td>
<td>{{ client.Email }}</td>
<td><button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false" class="btn btn-default">Save</button>
</td>
</tr>
</tbody>
However, every time I edit the field and submit it, it doesn't update the field in the table database.
Here's my controller save:
vm.saveAction = function () {
clientService.save(vm.clients, function (data) {
if (data.success) {
toastr.success('changes were saved.', 'Success');
vm.clients = data.records;
} else {
toastr.error('Error saving :\n\n' + data.errorMessage, 'Error', {
timeOut: 0
});
}
}, function (error) {
toastr.error('Error saving :\n\n' + error, 'Error', {
timeOut: 0
});
});
}

How to pass data into directives into ng-repeat table

Now I have some directives which are used in some place, in one place I need to load the data to init them( if there are no data, keep it blank). Here is the template of one of the directives:
<div class="col-lg-12" style='z-index: 99998;'>
<span class="col-lg-12 col-md-12 right-inner-addon typeAhead">
<i class="glyphicon glyphicon-search" ng-show="isBillToEmpty"></i> <i ng-click="cleanBillTo()"
class="glyphicon glyphicon-close" ng-show="!isBillToEmpty" ></i></a> <input class="data "
id="billTo" ng-model="billTo"
typeahead=" billTos.ID as billTos.VALUE for billTos in getBillTos($viewValue)"
typeahead-input-formatter="formatBillToText($model)" type="text">
</span>
</div>
<div class="col-lg-12">
<span class="col-md-12"> <label id="labelBillTo" for="billTo">{{billToLabel}}</label>
</span>
</div>
DirectiveJS:
function($scope, BillToService) {
$scope.billTos = {};
$scope.billTo = '';
$scope.billToLabel = 'Bill To'
$scope.isBillToEmpty = true;
$scope.formatBillToText = function(model) {
for (var i = 0; i < $scope.billTos.length; i++) {
if (model === $scope.billTos[i].ID) {
return $scope.billTos[i].VALUE;
}
}
}
$scope.$watch('billTo', function() {
$scope.billToID = $scope.billTo;
if($scope.billTo.length > 0){
$scope.isBillToEmpty = false;
}else{
$scope.isBillToEmpty = true;
}
});
$scope.cleanBillTo = function() {
$scope.billTo = "";
$scope.billToID = "";
};
$scope.billTos = [{'ID':$scope.billToID,'VALUE':$scope.initialBillToText}];
$scope.billTo = $scope.billToID;
$scope.getBillTos = function(billToText) {
var promise = BillToService.getBillTos(billToText,
$scope.user.expenServerID);
promise.then(function(billTosInformation) {
$scope.billTos = billTosInformation;
});
$scope.billTos = BillToService.getBillTos(billToText,
$scope.user.expenServerID);
return $scope.billTos;
};
} ]).directive('smartBillTo', function() {
return {
restrict : 'E',
controller : "BillToCtrl",
templateUrl : 'components/directives/billTo/bill-to.html'
}
<table id='AllocationTable' ng-controller='maincontroller' class="table table-hover">
<thead>
<tr>
<th class="text-left">
<input type="checkbox" ng-model="selectedAll" ng-click="checkAll()" />
</th>
<th class="text-center">Charge To Dept
</th>
<th class="text-center">Sub Account
</th>
<th class="text-center">Activity
</th>
<th class="text-center">Category
</th>
<th class="text-center">Bill To
</th>
<th class="text-center">Expense Item
</th>
<th class="text-center">Percentage
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat='data in datalist'>*How can I pass data to <smart-billTo>*
<td class="text-left">
<input type="checkbox" ng-model=''/>
</td>
<td class="text-center"><smart-department ></smart-department></td>
<td class="text-center"><input type='text' ng-model=''/></td>
<td class="text-center"><input type='text' ng-model=''/></td>
<td class="text-center"><input type='text' ng-model=''/></td>
<td class="text-center"><smart-bill-to></smart-bill-to></td>
<td class="text-center"><smart-item ></smart-item></td>
<td class="text-center"><input type='text' ng-model=''/></td>
</tr>
</tbody>
</table>
In the maincontroller I get data from service to init the directive value:
$scope.datalist = Someservice.getdata();
How can I pass data into directives to init the input value (such as bill-to).

Resources