How to push edited ng repeat data to another array onclick checkbox - angularjs

<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="SubCenter">SubCenter <span class="error">*</span></label>
<span ng-init="GetSubCenter()"></span>
<select class="form-control border-input" id="subcenter" name="subcenter" required multiple="" data-ng-model="AddCamp.subcenter" data-ng-change="GetVillage(AddCamp.subcenter)">
<option ng-repeat="subcenter in SubCenterArray" value="{{subcenter.id}}">{{subcenter.SubCenterName}}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6" ng-show="vlgdata">
<div class="form-group">
<label class="control-label" for="Village">Villages <span class="error">*</span></label>
<table class="table">
<thead>
<tr>
<th>Population</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="vlg in VillageArray | orderBy : 'Population'">
<td data-title="Population">
<input type="text" class="form-control border-input" value="{{ vlg.Population }}">
</td>
<td>
<input type="checkbox" ng-model="vlg.selectvlg" name="{{vlg}}" ng-click="chk()" />
</td>
</tr>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-6" ng-show="vlgdata">
<div class="form-group">
<label class="control-label" for="Village">Selected Villages <span class="error">*</span></label>
<table class="table">
<thead>
<tr>
<th>Population</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="p in selectedvlgs" | orderBy : 'Population'">
<td data-title="Population">{{ p.Population }}</td>
</tr>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
//Js start here
//Get subcenter details
$scope.subcenter = null;
$scope.SubCenterArray= [];
$scope.GetSubCenter= function()
{
$http.post("get_subcenter_name.php" , {})
.success(function(data)
{
$scope.SubCenterArray = data;
});
}
//Get vlg details
$scope.vlgdata = false;
$scope.village = null;
$scope.VillageArray= [];
$scope.GetVillage= function(subcenter)
{
$http.post("get_village_name.php" , {'subcenter': $scope.AddCamp.subcenter})
.success(function(data)
{
if(data!=null)
{
$scope.vlgdata = true;
$scope.VillageArray = data;
}
if(data==null)
{
$scope.vlgdata = false;
}
});
}
$scope.selectedvlgs = [];
$scope.chk = function(){
//alert("hii");
angular.forEach($scope.VillageArray, function(value, key){
if(value.selectvlg == true){
var title = value.id;
//alert(title);
var flg = 1;
angular.forEach($scope.selectedvlgs, function(value, key){
var exTitle = value.id;
if(title == exTitle){
flg = 0;
}
});
//alert (value.Product_Name);
if(flg == 1){
$scope.selectedvlgs.push(value);
}
}
if(value.selectvlg == false){
var title = value.id;
//alert(title);
var flg = 1;
angular.forEach($scope.selectedvlgs, function(value, key){
var exTitle = value.id;
if(title == exTitle){
flg = 0;
}
});
//alert(flg);
if(flg == 0){
var index = $scope.selectedvlgs.indexOf(value);
//alert(index);
$scope.selectedvlgs.splice(index,1);
$scope.sum=0;
for(i=0;i<$scope.selectedvlgs.length;i++)
{
$scope.Population=$scope.selectedvlgs[i].Population;
}
}
}
});
}
How to push edited ng repeat data to another array onclick checkbox.?
i am getting VillageArray data onclick of subcenter. In this villageArray i have to edit the population field and push editable value into the selectedvlgs. The editable value does not updating.
How to do this?

One thing to look at potentially is add a timeout and digest.
$timeout( () => {
$scope.$apply();
});
But I think the easier solution would be to utilize a function in the view to sum the bound values. You don't have to explicitly process the totals, you could just easily just sum vlg.selectvlg in the function from the view. Creating a function to loop through vlg.selectvlg
{{ displayVillageTotal() }}
$scope.displayVillageTotal = function() {
let total = 0;
selectvlg.forEach()...
return total;
}
Remove the explicit ng-click function (chk()) and the digest should pick up the change for the function in the view and update accordingly.

Related

I'm looking for a way to split ngFor checkboxes into tr and tds with Angular 2+

I'm looking for a way to split these checkboxes who come from server into a tr in which each tr has 5 tds, i'm displaying it through ngFor
this is the template:
this is the Component:
Diretiva: any = [];
loadDiretiva() {
return this.restApi.getDiretivas().subscribe((data: {}) => {
this.loading = true;
this.Diretiva = data;
});
}
the template:
<tbody class="text-center ">
<tr>
<td *ngFor="let diretiva of Diretiva">
<div class="checkbox c-checkbox">
<label>
<input type="checkbox">
<span class="fa fa-check"></span>
</label>
</div>
<label>{{diretiva.nome}}</label>
</td>
</tr>
</tbody>
Chunk the array first
function chunkArray(array, size) {
let result = []
for (let i = 0; i < array.length; i += size) {
let chunk = array.slice(i, i + size)
result.push(chunk)
}
return result
}
Chunks: any = [];
loadDiretiva() {
return this.restApi.getDiretivas().subscribe((data: {}) => {
this.loading = true;
this.Chunks= chunkArray(data,5);
});
}
Then
<tbody class="text-center ">
<tr *ngFor="let chunk of Chunks">
<td *ngFor="let diretiva of chunk">
<div class="checkbox c-checkbox">
<label>
<input type="checkbox">
<span class="fa fa-check"></span>
</label>
</div>
<label>{{diretiva.nome}}</label>
</td>
</tr>
</tbody>

angularjs dropdown menu: populate two input fields with different information from one option

I am brand new to AngularJS. I'm wanting to select an option from the dropdown RegistrationType and want that selection to determine what populates its own input AND input RegAmount.
So, I select the first option, $155.00 Two Day and "$155.00" would show up in the RegAmount input and "Two Day" should show up in the RegistrationType input.
I have failed multiple times, so far, over the last two days. Any advice is appreciated. One thing I tried was adding a name/id to the option and trying to tie that to RegAmount, but I wasn't able to separate the information.
I also tried a ng-if by duplicating the RegAmount div to show "$155.00" if the first option was selected, and ng-if if it wasn't selected, to show "$95.00". Couldn't get that to work either. Oh, and NO, RegAmount should not be an input of course, but I just hadn't changed it yet.
function ContactController($scope) {
$scope.changeme = function() {
}
var uid = 1;
$scope.contacts = [{
id: 0,
'regType': '5555',
'RegistrationType': '5555'
}];
$scope.saveContact = function() {
if ($scope.newcontact.id == null) {
$scope.newcontact.id = uid++;
$scope.contacts.push($scope.newcontact);
} else {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == $scope.newcontact.id) {
$scope.contacts[i] = $scope.newcontact;
}
}
}
$scope.newcontact = {};
}
$scope.delete = function(id) {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
$scope.contacts.splice(i, 1);
$scope.newcontact = {};
}
}
}
$scope.edit = function(id) {
for (i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
$scope.newcontact = angular.copy($scope.contacts[i]);
}
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app="" ng-controller="ContactController">
<form class="well">
<div>
<label>Registration Type</label>
<select name="RegistrationType" ng-model="newcontact.RegistrationType">
<option value = "">-- Select an Option --</option>
<option value = "Two Day">$155.00 Two Day</option>
<option value = "First Day">$95.00 First Day</option>
<option value = "Second Day">$95.00 Second Day</option>
</select>
</div>
<div>
<label>Registration Amount</label>
<input type="text" name="Registration Amount" ng-model="newcontact.RegAmount" />
</div>
<br>
<div>
<input type="hidden" ng-model="newcontact.id" />
<input id="buttonSave" type="button" value="Save" ng-click="saveContact()" class="btn btn-primary" />
<p style="clear: both;"></p>
</div>
</form>
<br/>
<br/>
<table>
<thead>
<tr>
<th>Registration Type</th>
<th>Registration Amount</th>
<th>Edit | Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.RegistrationType }}</td>
<td>{{ contact.RegAmount }}</td>
<td>
edit |
delete
</td>
</tr>
</tbody>
</table>
You could use NgOptions to solve this, here's an example
angular.module("app",[]).controller('testCtrl' , function($scope) {
var uid = 1;
$scope.newcontact = {};
$scope.days = [
{ id:1, text:"$155.00 Two Day (Now to 8 p.m. Sept 10)", price:"$155.00", day:"Two Day" },
{ id:2, text:"$95.00 First Day (Now to 8 p.m. Sept 10)", price:"$95.00", day:"First Day" },
{ id:3, text:"$95.00 Second Day (Now to 8 p.m. Sept 10)", price:"$95.00", day:"Second Day" }
];
$scope.contacts = [];
$scope.saveContact = function() {
if ($scope.newcontact.id == null) {
$scope.newcontact.id = uid++;
$scope.contacts.push($scope.newcontact);
} else {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == $scope.newcontact.id) {
$scope.contacts[i] = $scope.newcontact;
}
}
}
$scope.newcontact = {};
}
$scope.delete = function(id) {
for (var i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
$scope.contacts.splice(i, 1);
$scope.newcontact = {};
}
}
}
$scope.edit = function(id) {
for (i in $scope.contacts) {
if ($scope.contacts[i].id == id) {
$scope.newcontact = angular.copy($scope.contacts[i]);
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<div ng-app="app" ng-controller="testCtrl">
<form class="well">
<div>
<label>Registration Type</label>
<select ng-model="newcontact.RegistrationType" ng-options="item as item.text for item in days">
<option value = "">-- Select an Option --</option>
</select>
</div>
<div>
<label>Registration Amount</label>
<input type="text" name="Registration Amount" ng-model="newcontact.RegistrationType.price" />
</div>
<br>
<div>
<input id="buttonSave" type="button" value="Save" ng-click="saveContact()" class="btn btn-primary" />
<p style="clear: both;"></p>
</div>
</form>
<br/>
<br/>
<table>
<thead>
<tr>
<th>Registration Type</th>
<th>Registration Amount</th>
<th>Edit | Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.RegistrationType.text }}</td>
<td>{{ contact.RegistrationType.price }}</td>
<td>
edit |
delete
</td>
</tr>
</tbody>
</table>

how to disable pagination if there is only one page to display using AngularJs

I have a table of users and I can sort the display according to some status defined.
HTML
<div data-ng-controller="adminController">
<div class="row">
<div class="col-md-9">
<h3> <span style="color:blue">List of Applied Users</span></h3>
</div>
<div class="col-md-2">
<br>
<select class="form-control" id="sel1" data-ng-model="status" required>
<option value="">Status</option>
<option value="Open">Open</option>
<option value="In-Progress">In-Progress</option>
<option value="Rejected">Rejected</option>
<option value="Verified">Verified</option>
<option value="Closed">Closed</option>
</select>
</div>
</div>
<br>
<div class="padding">
<table class="table table-hover" border="2" >
<thead>
<tr>
<th width="30" bgcolor="#FF8566">Si.No</th>
<th width="90" bgcolor="#FF8566">Date</th>
<th width="140" bgcolor="#FF8566">Name</th>
<th width="340" bgcolor="#FF8566">Service Name</th>
<th width="90" bgcolor="#FF8566">Status</th>
th width="40" bgcolor="#FF8566"></th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="userDetails in (data | filter:status:status.status).slice(((currentPage-1)*itemsPerPage), ((currentPage)*itemsPerPage)) ">
<td></td>
<td> {{ userDetails.subDate | date : 'MM-dd-yyyy' }} </td>
<td> {{ userDetails.fullName }} </td>
<td> {{ userDetails.serviceType.serviceName }} </td>
<td> {{ userDetails.status.status }} </td>
<td>
<button type="button" class="btn btn-xs btn-success" data-ng-click="editUser(userDetails.id)" ng-if="userDetails.status.status !=='Closed'" >View</button></td>
</tr>
</tbody>
</table>
</div>
<uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage" ng-show ="blocked"></uib-pagination>
</div>
JS
app.controller('adminController',[ '$scope', '$http', function($scope, $http) {
$scope.$watch('status', function()
{
var array =[];
alert($scope.status);
if($scope.status!=undefined)
{
totaldata.forEach(function(value, arr)
{
if(value.status.status==$scope.status)
{
array.push(value);
}
console.log($scope.status);
})
$scope.data = array;
$scope.totalItems = array.length;
console.log(array.length);
}
else{
$scope.data = totaldata;
$scope.totalItems = totaldata.length;
console.log(totaldata.length);
}
})
$http.get('getAlldetails').success(function(response)
{
$scope.blocked = true;
$scope.data = response;
totaldata=response;
$scope.totalItems = response.length;
$scope.currentPage = 1;
$scope.itemsPerPage = 9;
$scope.maxSize = 5;
alert($scope.totalItems.length);
$scope.setPage = function (pageNo) {
$scope.currentPage = pageNo;
};
}).error(function(error)
{
alert(error);
});
$scope.editUser = function(id)
{
$location.url('/editUser/'+ id);
}
}]);
How to hide the pagination if there is only one page to display after applying a filter? I tried with ng-show and ng-if but no luck.
filter you data on ng-repeat like so
<tr ng-repeat="row in filteredData = (tableData | filter: filterQuery)">
<td>{{row.name}}</td>
<td>{{row.last_name}}</td>
<td>{{row.age}}</td>
<td>{{row.email}}</td>
</tr>
wrap you uib-pagination in div and set ng-show/ng-hide, show the pagination only if the amount of filteredData is larger then the items per page (having more items then the items per page means you have more then 1 page)
<div ng-show="filteredData.length > itemsPerPage">
<uib-pagination total-items="totalItems" ng-model="currentPage" ng-change="pageChanged()" class="pagination-sm" items-per-page="itemsPerPage" ng-show ="blocked"></uib-pagination>
</div>
so when you will change the filter criteria, the digest cycle will run an reevaluate your ng-show

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).

Edit Ng-Repeat inline with REST API

I have been at this for awhile now but in short I am making a UI that allows our users to modify a MySQL DB using an Angular frontend and Slim PHP to serve up the REST.
I continue to get an error stating that 'firstName' is not defined as a column and I cant seem to figure out why. I believe it has something to do with the way the ng-repeat works and how I can assign / call objects inside of it but I am stuck!
Here is the HTML, App.js and index.php - The code is a little hacked up but I want to edit the rows in-line.
Any knowledge is much appreciated as I have just started using Angular and REST this year!
List.html
<div class="row">
<div class="col-lg-12">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address 1</th>
<th>Address 2</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th class="text-center">Edit</th>
</tr>
</thead>
<tbody ng-repeat="referral in referrals | filter:query | limitTo:limitBy | orderBy:lastName">
<tr >
<td>{{referral.ID}}</td>
<td>
<!-- <span id="firstName" data-ng-hide="editMode">{{referral.firstName}}</span>-->
<span data-ng-hide="editMode">{{referral.firstName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.firstName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.lastName}}</span>
<input type="text" data-ng-show="editMode" ng-model="referral.lastName"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address1}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address1"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.address2}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.address2"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.city}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.city"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.state}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.state"/>
</td>
<td>
<span data-ng-hide="editMode">{{referral.zipCode}}</span>
<input type="text" data-ng-show="editMode" data-ng-model="referral.zipCode"/>
</td>
<td class="text-center">
<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; saveField(referral)" class="btn btn-default">Save</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false; cancel()" class="btn btn-default">Cancel</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
App.js
app.controller('viewController', function($resource, $scope, $location, $route, $routeParams) {
$scope.title = 'Endo Admin';
$scope.query = {};
$scope.queryBy = 'lastName';
$scope.limitBy = '50';
var Referrals = $resource('http://pdgrosit02v/endoAdmin/app/api/referrals');
$scope.referrals = Referrals.query();
$scope.newField = {};
$scope.editing = false;
$scope.editAppKey = function(field) {
$scope.editing = $scope.referrals.indexOf(field);
$scope.newField = angular.copy(field);
}
$scope.saveField = function(index) {
// if ($scope.editing !== false) {
// var Referral = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID));
//
// $scope.referral = Referral.get();
//
$scope.referral = $scope.newField;
// $scope.editing = false;
var ReferralPut = $resource(('http://pdgrosit02v/endoAdmin/app/api/referral/'+ index.ID), {}, { update: { method: 'PUT'}} );
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
};
});
index.php
<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
use Slim\Slim;
$app = new Slim();
$app->get('/referrals', 'getReferrals');
$app->get('/referral/:id', 'getReferral');
$app->put('/referral/:id', 'updateReferral');
$app->run();
function updateReferral($id) {
$referral = Slim::getInstance()->request()->getBody();
$data = json_decode($referral, true);
$sql = "UPDATE endo_referral SET firstName=:first_Name, lastName=:last_Name WHERE ID=$id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindValue(":first_Name", $data['firstName']);
$stmt->bindValue(":last_Name", $data['lastName']);
$stmt->execute();
$db = null;
echo json_encode($data);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
In the $scope.saveField function, you should use the passed-in referral. Instead of
...
ReferralPut.update($scope.referral, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
...
Looking at your code, it looks like this needs to be:
ReferralPut.update(index, function() {
// success
$location.path('/endoadmin');
}, function() {
// error
console.log(error);
});
The $scope.saveField function is passed the current referral in the index field. $scope.referral is undefined in the saveField function.
There may be other issues, but this was the one that stood out the most.

Resources