On change ng-model value should be change - angularjs

I have below code.
<td class="minwd100">
<select class="form-control" id="invoice_id" name="invoice_id" ng-options="invoice as invoice.invoice_number+ ' - '+invoice.client_name+' - '+invoice.invoice_converted_total for invoice in approved_invoices track by invoice.invoice_id" ng-model="approved_invoices.invoice_id" ng-change="changeInvoice(approved_invoices.invoice_id)"></select>
</td>
<td class="minwd100"><input type="text" class="form-control" id="payment_amount" ng-model="payment_data.payment_amount.value" name="payment_amount" placeholder="Enter {{form_data.payment_amount.label}}" ng-focus="form_data.payment_amount.error = ''" /></td>
<td class="minwd100"><input type="text" class="form-control" id="payment_conversion" ng-model="payment_data.payment_conversion_rate.value" name="payment_conversion" placeholder="Enter {{form_data.payment_conversion_rate.label}}" ng-focus="form_data.payment_conversion_rate.error = ''" /></td>
<td class="minwd100"><input type="text" class="form-control" id="payment_converted_amount" ng-model="payment_data.payment_converted_amount.value" name="payment_converted_amount" placeholder="Enter {{form_data.payment_converted_amount.label}}" ng-focus="form_data.payment_converted_amount.error = ''" ng-readonly="true"/></td>
<td class="wd80">
<div class="dt-options">
<a href ng-if="$index === form.payments.length - 1" ng-click="addContact()" title="Add Contact"><i class="fa fa-plus fa-lg"></i></a>
<a href ng-if="form.payments.length > 1" ng-click="removeContact($index)" title="Remove Contact"><i class="fa fa-trash-o fa-lg"></i></a>
</div>
</td>
<script>
$scope.changeInvoice = function (selectedItem){
$scope.payment_data.payment_amount.value = selectedItem.invoice_converted_total;
$scope.payment_data.payment_conversion_rate.value = selectedItem.invoice_conversion_rate;
$scope.payment_data.payment_converted_amount.value = selectedItem.invoice_converted_balance;
$scope.client_id = selectedItem.client_id;
$scope.payment_data.invoice_id.value = selectedItem.invoice_id;
};
$scope.addContact = function() {
$scope.form.payments.push({invoice_id: '', payment_amount: '', payment_conversion: '', payment_converted_amount: ''});
};
$scope.removeContact = function(index) {
$scope.form.payments.splice(index, 1);
};
</script>
To each change, value should be triggered for each input, But now whenever I add new row, its reflect old value itself please help. I have added image also please refere that.

What is the collection that you are iterating through?
"To each change, value should be triggered for each input, But now whenever I add new row, its reflect old value itself please help. I have added image also please refere that."
Are you saying that when you change one row every row changes? That is how I am understanding it. My guess is that all of the items in the collection are referencing the same object and you need to refer to the specific item within the collection.
I recently set up a model that had a form where you could add many associations so when adding a new association to the form I had to use a unique key to refer to the hash. I.e.:
$scope.addNewPartToAssembly = function(part) {
$scope.form.assembly.assembly_parts[part.id] = {
...
}
}
I'm just kind of guessing at your problem because to me it seems incomplete, maybe somebody else could resolve it with what's provided. Either way, hope that helps.

Related

how to $Index get from Javascript side

how to Checked value from $index base. suppose in textboxStart Index and TextboxEnd . when user enter Start index 5 and End Index 10 , checkbox automatically checked, from 5 To 10 Index. please help me
<tr ng-repeat="item in MyList">
<td>{{$index}}</td>
<td>
<label class="mdl-checkbox mdl-js-checkbox" for="checkbox33">
<input autocomplete="off" ng-model="item.checked"
type="checkbox" id="checkbox33"
class="mdl-checkbox__input" unchecked>
{{CheckItems()}}
</label>
<td>{{item.Name}}</td>
<td>{{item.PilgrimID}}</td>
<td>{{item.GroupName}}</td>
<td>{{item.PassportNo}}</td>
<td>{{item.Gender}}</td>
<td>{{item.SubAgentName}}</td>
Use the ng-change directive to specify an update function:
<div>Input Start
<input ng-model="inputStart" ng-change="updateSelections(inputStart,inputEnd)" />
</div>
<div>Input End
<input ng-model="inputEnd" ng-change="updateSelections(inputStart,inputEnd)" />
</div>
Then update the selections:
$scope.updateSelections = function(iStart, iEnd) {
$scope.MyList.forEach((x,index)=>item.checked = (iStart<=index && index<=iEnd));
};
just push the selected values in an array , selectedItemIndexes like ng-checked="selectedItemIndexes.includes($index)"
https://stackblitz.com/edit/angularjs-snavdn
you can do it by adding one property like ItemIndex in your ItemList model,
and by putting input box with display none you can get index value in ItemList and can do what you want from javascript side,
<td><input type="text" style="display:none;" ng-model="item.ItemIndex"
ng-value="$index"/>{{$index}}
</td>

how to get select value with input values in angularjs

Can any one help how to get input and selected values by dynamically added with angularjs?
Here is my code in Plunkr
When I select vegtables, another input shows with some values. when I click submit button I need a json like
{
"itemName":"Mango",
"itemType":"fruits"
},
{
"itemName":"Carrot",
"itemType":"vegtables",
"iteminfo":"you selected Carrot"
},
{
"itemName":"Apple",
"itemType":"fruits"
}
I forked your plunker
You can bind itemInfo to an item object using ng-model. Rather than placing the text in a value attribute I just initialized the model value using ng-init.
<tr ng-repeat="item in Items">
<td>
<input type="text" ng-model="item.itemName">
</td>
<td>
<select ng-model="item.itemType">
<option value="">--Select--</option>
<option vaue="fruits">Fruits</option>
<option value="vegtables">Vegtables</option>
</select>
</td>
<td>
<div ng-switch on="item.itemType">
<input type="text" ng-model="item.itemInfo" ng-switch-when="vegtables" ng-init="item.itemInfo='you selected '+ item.itemName">
</div>
</td>
</tr>
Also I had to change the Items array to match your requested naming:
$scope.Items = [{itemName: "Mango"}, {itemName: "Carrot"}, {itemName: "Apple"}];
You can parse the JSON object in a for loop to get the selected value and add the new key value pair.
angular.forEach($scope.vegetables, function(value, key){
if(value.itemName== 'Carrot')
value.iteminfo = 'you selected Carrot';
});
I guess you might be looking for something like this, if I am not wrong.

Working of ng-repeat with dynamic data

I have a query regarding angularjs, i.e. I have a table in which I have rows, but these rows are dynamically inserted by user. That means If I have a company having more than one owners then I allow them to add as many owners as they want by simply clicking on add button which is placed with the textboxes (i.e. name, email, number textboxes)
I have used 'ng-repeat' on a row so that the list of owners can be dynamically added one by one. While fetching values from the database it is working perfectly fine but when I am trying to add values by clicking 'add' button, It adds the new row with all the text boxes BUT WITH THE SAME VALUES as the previous row. I think it is because I have used ng-model to link the data.. but then that is the only option I can bind the data.. Do anyone have solution for this problem.? Please help me.
Thank you in advance
I am sharing the code sample for better understanding,
JSP code:
<tbody id="insertionRow">
<tr>
<th>#</th>
<th class="required">Name</th>
<th>Email</th>
<th>Phone No</th>
<th>Add</th>
<th>Delete</th>
</tr>
<tr data-ng-repeat="c in ctrl.client.clientOwnerVOList">
<td>{{$index + 1}}</td>
<td class="col-lg-3"><input type="Text"
class="form-control"
data-ng-model="c.clientOwnerName"
name="clientOwnerName{{$index + 1}}" id="Name">
</td>
<td class="col-lg-4"><input type="Email"
class="form-control"
data-ng-model="c.clientOwnerEmail"
name="clientOwnerEmail{{$index + 1}}" id="Email"></td>
<td class="col-lg-3"><input type="Text"
class="form-control"
data-ng-model="c.clientOwnerPhone"
name="clientOwnerPhone{{$index + 1}}" id="PhoneNo"></td>
<td>
<button type="button"
data-ng-click="insert();"
class="btn btn-sm btn-default">
<i class="fa fa-plus fa-lg"></i>
</button></td>
<td><button type="button"
onClick="$(this).closest('tr').remove();"
class="btn btn-sm btn-default">
<i class="fa fa-trash fa-lg "></i>
</button></td>
</tr>
</tbody>
AngularJS controller code:
$scope.insert = function(){
var tableRow ="<tr data-ng-repeat='c in ctrl.client.clientOwnerVOList'>"+
"<td>"+i+"</td>"+
"<td class='col-lg-3'><input type='Text' class='form-control' data-ng-model='c.clientOwnerName' name='clientOwnerName{{$index + 1}}' ></td>"+
"<td class='col-lg-4'><input type='Email' class='form-control' data-ng-model='c.clientOwnerEmail' name='clientOwnerEmail{{$index + 1}}'</td>"+
"<td class='col-lg-3'><input type='Text' class='form-control' data-ng-model='c.clientOwnerPhone' name='clientOwnerPhone{{$index + 1}}' ></td>"+
"<td><button type='button' data-ng-click='insert()' class='btn btn-sm btn-default'><i class='fa fa-plus fa-lg'></i></button></td>"+
"<td><button type='button' class='btn btn-sm btn-default' onClick=$(this).closest('tr').remove();><i class='fa fa-trash fa-lg '></i></button></td>"+
"</tr>";
var compiledString = $compile(tableRow)($scope);
$("#insertionRow").append(compiledString);
i++;
};
And the client Object is as follows
self.client= {
clientID:'',
clientName:'',
clientDescription:'',
clientAddressLine:'',
clientContactPersonPhone:'',
createdOn:'',
astUpdatedOn:'',
country:'',
state:'',
city:'',
isDeleted:'',
clientOwnerVOList: [
{
clientOwnerID:'',
createdOn:'',
isDeleted:'' ,
clientOwnerName:'',
clientOwnerPhone:'',
clientOwnerEmail:''
}
]
}
I tried to reproduce your problem in this plunker :
https://plnkr.co/edit/Eqw21bGNetGtHZIQZCYw?p=preview
I changed your insert function to create new clientOwnerVO.
I just push new object like this :
$scope.client.clientOwnerVOList.push({clientOwnerID:'',
createdOn:'',
isDeleted:'' ,
clientOwnerName:''
,clientOwnerPhone:''
,clientOwnerEmail:'',});
i++;
I hope i understand your problem
The insert function is pretty strange. AFAIT you are inserting some compiled HTML into the DOM. Angular's whole thing is for you to avoid doing this by hand. You should be changing ctrl.client.clientOwnerVOList directly by appending the required JS objects to it and then the change will be reflected by the DOM.
The code should look similar to this, plus-minus application specific logic which you know better.
$scope.append = function() {
self.client.clientOwnerVOList.push({
clientOwnerId: 'newid',
createdOn: 'today',
isDeleted: 'false',
clientOwnerName: 'foo',
clientOwnerPhone: 'bar',
clientOwnerEmail: 'foo#bar.com'
});
}
The values to populate the client info would be taken from other places (other models fields, or some sensible defaults etc.)
Basically, you have a bunch of data (self.client, and any other controller variables from the scope). The view is a function of this data, and you describe how to build the DOM through the html template which can access the fields from the scope. It's Angular's job to figure out how to do that. Whenever some sort of event happens, like a button press or network event etc., you update the data, and then Angular rebuild the DOM for you.

how to set table row colors depending on label "yes/no" clicks per row

I have been attempting to get the following piece of code to work but have as yet no been able to find a good solution. I have succesfully done this type of functionality via jQuery but my new requirements are to figure out how to do it in an angular way.
I have a table which is contructed via ng-repeat, each row contains a set of yes/no buttons in order to "approve" or "decline" the data visible in each row. When a row is either approved or declined, the color of that row will change to either green or red.
Currently all my rows are changing colors instead of only the row where Yes/No was clicked. I have tried doing something with the index and sending through the id (term in this case) and countless other things but I am unsure what to do inside the controller and how to add the class name specific to each row. Help would be greatly appreciated.
HTML:
<tr ng-repeat="tableData in maximumOfferData" ng-class="{0:'test-none', 1:'test-yes',2:'test-no'}[classstatusmaximum]">
<td>{{tableData.term}}</td>
<td>{{tableData.offer}}</td>
<td>{{tableData.payment}}</td>
<td>{{tableData.coverage}}</td>
<td>
<div class="btn-group pull-right">
<label data-ng-model="testyes"
data-btn-radio="'Left'"
class="btn btn-default ok ng-pristine ng-untouched ng-valid"
ng-click="changeMaximumStatusYes(tableData.term)">
YES
</label>
<label data-ng-model="testyes"
data-btn-radio="'Middle'"
class="btn btn-default nok ng-pristine ng-untouched ng-valid"
ng-click="changeMaximumStatusNo(tableData.term)">
NO
</label>
</div>
</td>
</tr>
Controller.js:
$scope.maximumOfferData= [
{'term':'7', 'offer':'11500', 'payment':'11.57', 'coverage':'18' },
{'term':'8', 'offer':'12500', 'payment':'16.88', 'coverage':'24' },
{'term':'9', 'offer':'9500', 'payment':'18.72', 'coverage':'12' }
];
$scope.classstatusmaximum = "0";
$scope.changeMaximumStatusYes = function(offerid){
console.log(offerid);
if ($scope.classstatusmaximum !== "1")
$scope.classstatusmaximum = "1";
};
$scope.changeMaximumStatusNo = function(offerid){
console.log(offerid);
$scope.classstatusmaximum = offerid;
if ($scope.classstatusmaximum !== "2")
$scope.classstatusmaximum = "2";
};
See above Plunker attempt Here:
http://plnkr.co/edit/3OjtzSUWdWCYTpXqxtOd?p=preview
change this line in the html:
<tr ng-repeat="tableData in maximumOfferData"
ng-class="{0:'test-none', 1:'test-yes',2:'test-no'}[tableData.status]">
and this
<label data-ng-model="testyes"
data-btn-radio="'Left'"
class="btn btn-default ok ng-pristine ng-untouched ng-valid"
ng-click="changeMaximumStatusYes(tableData)">
YES
</label>
<label data-ng-model="testyes"
data-btn-radio="'Middle'"
class="btn btn-default nok ng-pristine ng-untouched ng-valid"
ng-click="changeMaximumStatusNo(tableData)">
NO
And in your controller:
$scope.maximumOfferData= [
{'term':'7', 'offer':'11500', 'payment':'11.57', 'coverage':'18','status':'0' },
{'term':'8', 'offer':'12500', 'payment':'16.88', 'coverage':'24','status':'0' },
{'term':'9', 'offer':'9500', 'payment':'18.72', 'coverage':'12','status':'0' }
];
$scope.changeMaximumStatusYes = function(data){
data.status = "1";
};
$scope.changeMaximumStatusNo = function(data){
data.status = "2";
};
In this way you set a different status on every line, rather than set the status on a single var

ng-form not available after manually deleting an item from collection of ng-repeat

Edit Here is the plunk for this question
I have a master detail form for an accounting transaction. The master portion just contains two fields name and Type. The detail portion can have two or more entries and each entry has AccountId, Debit and Credit fields. The form looks like
You can see that there is a delete button against each entry so if we have more than two entries we can delete any entry at random. The form html looks like following
<body data-ng-app="transactions">
<div data-ng-controller="transactionsController">
<form role="form" name="transactionForm" novalidate data-ng-submit="create()">
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-4">
<h2 class="form-login-heading">Create Transaction</h2>
<div data-ng-repeat="error in errors" class="alert alert-danger">
{{error[0]}}
</div>
<input type="text" name="name" class="form-control" placeholder="Name" data-ng-model="transaction.Name" required autofocus>
<div>
<span class="error" data-ng-show="transactionForm.name.$error.required && submitted">Please enter Name</span>
</div>
<input type="text" name="type" class="form-control" placeholder="Type" data-ng-model="transaction.Type" required>
<div>
<span class="error" data-ng-show="transactionForm.type.$error.required && submitted">Please enter Type</span>
</div>
<!--<input type="text" readonly name="number" class="form-control" placeholder="Number" data-ng-model="transaction.Number">
<input type="checkbox" data-ng-model="transaction.IsFinalized" /> <label>Finalize</label>-->
<table>
<tr>
<th>Account</th>
<th>Debit</th>
<th>Credit</th>
<th> </th>
</tr>
<tr data-ng-form="entryForm" data-ng-repeat="entry in transaction.Entries track by $index">
<td>
<input required name="accountId" data-ng-model="entry.AccountId" class="form-control" />
<span class="error" data-ng-show="entryForm.accountId.$error.required && submitted">Please select an account</span>
</td>
<td>
<input type="text" name="debit" data-ng-required="!entry.CreditAmount" class="form-control" placeholder="Debit" data-ng-model="entry.DebitAmount">
<span class="error" data-ng-show="entryForm.debit.$error.required && submitted">Debit is required</span>
</td>
<td>
<input type="text" data-ng-focus="checkAddRow($index)" name="credit" data-ng-required="!entry.DebitAmount" class="form-control" placeholder="Credit" data-ng-model="entry.CreditAmount">
<span class="error" data-ng-show="entryForm.credit.$error.required && submitted">Credit is required</span>
</td>
<td><button data-ng-show="transaction.Entries.length>2" class="btn btn-md btn-info " type="button" data-ng-click="deleteRow($index)">delete</button></td>
</tr>
<tr>
<td>Total</td>
<td><input readonly name="totalDebit" type="text" class="form-control" placeholder="Total Debit" data-ng-value="totalDebit()"></td>
<td><input readonly name="totalCredit" compare-to="totalDebit" type="text" class="form-control" placeholder="Total Credit" data-ng-value="totalCredit()"></td>
</tr>
<tr>
<td></td>
<td><b>Difference</b></td>
<td>
<input name="difference" readonly type="text" class="form-control" data-ng-value="difference()">
<!--<span class="error" data-ng-show="submitted && !differencezero">Difference should be 0</span>-->
</td>
</tr>
</table><br />
<button class="btn btn-md btn-info" type="submit">Create</button>
<button class="btn btn-md btn-info" data-ng-show="transaction.Entries.length<15" type="button" data-ng-click="addRow()">Add Row</button>
<div data-ng-hide="message == ''" class="alert alert-danger">
{{message}}
</div>
</div>
<div class="col-md-4">
</div>
<div class="col-md-2">
</div>
</div>
</form>
<style type="text/css">
.error {
color: red;
}
</style>
<pre>{{transactionForm.entryForm|json}}</pre>
</div>
I have the requirement that when focus is on Credit input of last entry the new entry should automatically added to the UI. I do it by using addRow and checkAddRow method on my controller. these methods are as follows
$scope.checkAddRow = function (index) {
if (index == $scope.transaction.Entries.length - 1) {
$scope.addRow();
}
}
$scope.addRow = function () {
entry = {
EntryTime: '',
DebitAmount: '',
CreditAmount: '',
AccountId: ''
};
$scope.transaction.Entries.push(entry);
console.log($scope.transactionForm);
}
$scope.deleteRow = function (index) {
$scope.transaction.Entries.splice(index, 1);
console.log($scope.transactionForm);
}
Again this part is just fine and works well. But I have another requirement that says that if last entry is not used it should not cause the form to invalidate. It should rather be removed from transaction.Entries collection and rest of the data should be saved normally. To achieve this, I have create function defined on $scope that looks like following
$scope.create = function () {
$scope.submitted = true;
if ($scope.transactionForm.entryForm && $scope.transactionForm.entryForm.$invalid && $scope.transactionForm.entryForm.$pristine) {
$timeout(function () {
$scope.deleteRow($scope.transaction.Entries.length - 1);
});
$timeout(function () {
console.log('From time out', $scope.transactionForm.$valid);
console.log($scope.transactionForm.$valid);
if (!$scope.transactionForm.$valid) return;
alert('data saved!');
console.log($scope.transactionForm);
//$scope.transactionForm.name.focus();
}, 200);
}
else {
if ($scope.transactionForm.$valid) {
alert('data saved 2');
}
}
}
You can see that what create function is doing. It is checking if entryForm (ng-form) is present in the main form (transactionForm) then it checks if entryForm is $invalid and $pristine if all these flags are true then, I delete the last entry from $scope.transaction.Entries and save the data (currently an alert to show data is saved) after $timeout. If I don't use timeout then the form is invalid so I have to wait for 200ms before I check the forms $valid flag after removing last row. But to my surprise when I remove last row from create function, there is no entryForm attached to the outer transactionForm. On the other hand If I delete entries using delete buttons present on UI, the entryForm is present inside the main transactionForm. Can anyone explain why is that. I have added <pre>{{transactionForm|json}}</pre> at the end to see when it is and when it is not available on main form. I have created a plunk to show what I mean. just add some data in two input fields of the master portion, enter some data in accountid field of both entries, when you reach the Credit input of second (last) entry, a new entry will be automatically added. Ignore that row and just push create button. The last entry will be removed and data will save but the entryForm will not be there anymore. I am not sure what I am doing wrong.
So, a problem here is that your definition of whether the form is valid or not depends on the state of the last row.
The last row could be of the following variety:
row fetched from the backend, but not new --> should only invalidate if not valid
row is new and $pristine --> should not invalidate
row is new, but $dirty (and still last) --> should only invalidate if not valid
You are trying to remove the last row and then re-evaluate the form for validity.
Approach it the other way - don't let the last row invalidate the form if it's in $pristine state:
Here's a simplified example:
<form name="transactionForm" ng-submit="submit()" novalidate>
<table>
<tr ng-form="entryForm" ng-repeat="transaction in transactions">
<td><input ng-model="transaction.account"
ng-required="transaction !== newLastEntry || entryForm.$dirty"></td>
<td><input ng-model="transaction.amount"
ng-required="transaction !== newLastEntry || entryForm.$dirty"
ng-focus="addEntryIfLast($last)" type="number"></td>
</tr>
</table>
</form>
Note $scope.newLastEntry here. It is set to the new empty (and last) entry. This happens when you add a new empty row:
function addEmptyEntry(){
$scope.newLastEntry = {};
$scope.transactions.push($scope.newLastEntry);
}
And so, ng-required is applied only if row is NOT new last OR otherwise $dirty.
Then, on submit, you can remove the last entry if it's in $pristine state and indeed the new last (as opposed to whatever existed before):
$scope.submit = function(){
var itemsToSubmit = angular.copy($scope.transactions);
if ($scope.transactionForm.$invalid) return;
if ($scope.transactionForm.entryForm &&
$scope.transactionForm.entryForm.$pristine &&
$scope.transactions[$scope.transactions.length - 1] === $scope.newLastEntry) {
itemsToSubmit.splice(itemsToSubmit.length - 1);
}
console.log(JSON.stringify(itemsToSubmit));
};
plunker

Resources