Differentiating current textbox value from old one and showing in Angular JS - javascript

My code is like this
<body>
<div>
<table ng-app='myApp' ng-controller="MainCtrl">
<thead></thead>
<tbody ng-repeat="prdElement in palletElement track by $index">
<tr>
<td>{{prdElement.name}}</td>
</tr>
<tr ng-repeat="data in prdElement.Data">
<td>{{data.itemId}}</td>
<td>{{data.shipmentId}}</td>
<td>{{data.itemCode}}</td>
<td>{{data.description}}</td>
<td>{{data.handlingUnit}}</td>
<td>{{data.weight}}</td>
<td>{{data.class}}</td>
<td>{{data.lenght}}</td>
<td>{{data.width}}</td>
<td>{{data.height}}</td>
<td>{{data.flag}}</td>
<td>
<input type="text" ng-model="data.quantity" placeholder=" Code" required />
</td>
</tr>
<tr>
<td>
<button ng-click="newPalletItem( prdElement,$event)">Submit</button>
</td>
</tr>
<!--<tr id="displayitems" >
<td>
{{palletElement}}
</td>
</tr>-->
</tbody>
</table>
</div>
(function () {
angular.module('myApp', []).controller('MainCtrl', function ($scope) {
var counter = 0;
$scope.palletElement = [{
name: 'Pallet 1',
Data: [{
name: 'item 1',
itemId: '284307',
shipmentId: 'eb44f690-c97a-40e3-be2a-0449559e171a',
itemCode: '',
description: 'Bicycle parts - frame',
quantity: '31',
handlingUnit: 'CTN',
weight: '613.04',
class: '',
lenght: '102',
width: '42',
height: '61',
flag: 'P'
}, {
name: 'item 2',
itemId: '284308',
shipmentId: 'eb44f690-c97a-40e3-be2a-0449559e171a',
itemCode: '',
description: 'Bicycle parts - fork',
quantity: '22',
handlingUnit: 'CTN',
weight: '242.99',
class: '',
lenght: '75',
width: '34',
height: '18',
flag: 'P'
}]
}]
$scope.newPalletItem = function (palletElement, $event) {
counter++;
$scope.palletElement.push(palletElement);
}
});
}());
When some one changes the value in last column textbox and press submit button I want to calculate [preloded value in textbox - (minus) current value in that text box ] and show it in next row. So far I have managed to duplicate the entire data completely to next row. but have no Idea in how to achieve rest. Can any one pint out a solution.
Fiddle
More details from Fiddle: as you can see current value is first text box is 31 if some one changes it to 10 when I duplicate the row to bottom I want that new textbox value to be shown as 21 (which is 31-10).

Please see here: http://jsfiddle.net/8r8cxcup/
newPalletImte:
$scope.newPalletItem = function (palletElement, $event) {
var npalletElement = {};
angular.copy(palletElement, npalletElement);
counter++;
angular.forEach(npalletElement.Data, function (row) {
if (row.quantity != row.newquantity) {
row.quantity = row.quantity - row.newquantity;
}
});
$scope.palletElement.push(npalletElement);
};
});
HTML:
<table ng-app='myApp' ng-controller="MainCtrl">
<thead></thead>
<tbody ng-repeat="prdElement in palletElement track by $index">
<tr>
<td>{{prdElement.name}}</td>
</tr>
<tr ng-repeat="data in prdElement.Data" ng-init="data.newquantity = data.quantity">
<td>{{data.itemId}}</td>
<td>{{data.shipmentId}}</td>
<td>{{data.itemCode}}</td>
<td>{{data.description}}</td>
<td>{{data.handlingUnit}}</td>
<td>{{data.weight}}</td>
<td>{{data.class}}</td>
<td>{{data.lenght}}</td>
<td>{{data.width}}</td>
<td>{{data.height}}</td>
<td>{{data.flag}}</td>
<td>
<input type="text" ng-model="data.newquantity" placeholder=" Code" required />
</td>
</tr>
<tr>
<td>
<button ng-click="newPalletItem( prdElement,$event)">Submit</button>
</td>
</tr>
<!--<tr id="displayitems">
<td>
{{palletElement}}
</td>
</tr>-->
</tbody>
</table>

Related

Passing calculated value to ng-model

I am new to AngularJS and am trying to set up a simple Orders form. I'm having problems passing the id value to the controller. I want it to be the last order id + 1 so it acts as an identity field. Ideally I'd like it to be hidden, but if I could just get this part working that would help.
Here is what I have tried:
HTML:
<div ng-controller = "OrdersCtrl">
<h1>Orders</h1>
<form class="form-inline" ng-submit="addOrder()">
<strong>Add order: </strong>
<input value="{{orders[orders.length - 1].id + 1 }}" ng-model="newOrder.id" >
<input type="number" step="0.01" class="form-control" placeholder="Total" ng-model="newOrder.total">
<input type="number" class="form-control" ng-model="newOrder.product_id">
<input type="submit" value="+" class="btn btn-success">
</form>
<table class="table table-hover">
<thead>
<td>Order ID</td>
<td>Total</td>
<td>Product</td>
<td></td>
</thead>
<tr ng-repeat="order in orders | orderBy: '-id':reverse">
<td>
{{order.id}}
</td>
<td>
<strong>{{order.total | currency}}</strong>
</td>
<td>
{{order.product_id}}
<small ng-show="order.user_id"><br>-{{order.user_id}}</small>
</td>
<td>
<button ng-click="deleteOrder(order)" class="btn btn-danger btn-sm"><span class="gylphicon glyphicon-trash" aria-hidden="true"></span></button>
</td>
</tr>
</table>
</div>
JS:
var app = angular.module('shop', []);
$(document).on('ready page:load', function() {
angular.bootstrap(document.body, ['shop'])
});
app.controller('OrdersCtrl', ['$scope', function($scope){
$scope.orders = [
{id: 1, total: 55, product_id: 5, user_id: 1},
{id: 2, total: 33, product_id: 3, user_id: 1},
{id: 3, total: 51, product_id: 12, user_id: 1}
];
$scope.addOrder = function(){
if(!$scope.newOrder.product_id || $scope.newOrder.total === ''){return;}
$scope.orders.push($scope.newOrder);
};
$scope.delOrder = function(order){
$scope.orders.splice($scope.orders.indexOf(order), 1);
};
}]);
I'm not getting any errors but nothing is appearing in the id column. Any advice would be appreciated.
Since $scope keeps all the existing orders, you shouldn't need to pass in a new id. Just calculate it in the controller when adding a new order.
remove this line from the view
<input value="{{orders[orders.length - 1].id + 1 }}" ng-model="newOrder.id" >
In controller
$scope.newOrder = {};
$scope.addOrder = function(){
if($scope.newOrder.total === ''){ return; }
$scope.newOrder.id = $scope.orders[$scope.orders.length - 1].id + 1
$scope.orders.push($scope.newOrder);
$scope.newOrder = {};
};

Duplicated form after click button add

Anybody help me, I have these working code currently:
HTML:
<body ng-controller="ExampleCtrl">
<label>Category:</label>
<select ng-model="product.category" ng-options="category as category.name for category in categories"></select>
</label><br/><br />
<table class="table" ng-repeat="attr in product.category.templateAttribute">
<thead>
<tr>
<th colspan="4">{{attr.attribute}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input value="{{attr.attribute}}" />
</td>
<td>
<input placeholder="name" ng-model="product.attributes[attr.attribute].name" />
</td>
<td>
<input placeholder="additional price" ng-model="product.attributes[attr.attribute].additionalPrice" />
</td>
<td rowspan="2">
<button type="button" ng-click="addItem(product.category.templateAttribute, attr)">
add
</button>
</td>
</tr>
<tr>
<td colspan="3">
<input type="file" class="form-control" ng-model="product.attributes[attr.attribute].file"/>
</td>
</tr>
</tbody>
</table>
JS
function ExampleCtrl($scope){
$scope.categories = [
{
name:'custom',
templateAttribute: [
{attribute: 'material'},
{attribute: 'soles'},
{attribute: 'size'}
]
}
];
$scope.products = [
{
name: 'custom',
category: {
name:'custom',
templateAttribute: [
{
type: "string",
attribute: "material"
},
{
type: "string",
attribute: "soles"
},
{
type: "string",
attribute: "size"
}
]
}
}
];
// add menu item
$scope.addItem = function(list, item){
list.push(angular.copy(item));
item = {};
};
// remove menu item
$scope.removeItem = function(list, index){
list.splice(index ,1);
};
}
angular
.module('app', [])
.controller("ExampleCtrl", ExampleCtrl)
For a demo :
Seet Demo
My problem is when I fill out one form above and click on the add button, it will display a new form, but that form always has the same value. How to fix my problem?
item should be defined as {} before pushing in list array.
If you do not want to send any model data through view then there is no point of sending attr argument to controller
Try this:
// Code goes here
function ExampleCtrl($scope) {
$scope.categories = [{
name: 'custom',
templateAttribute: [{
attribute: 'material'
}, {
attribute: 'soles'
}, {
attribute: 'size'
}]
}];
$scope.products = [{
name: 'custom',
category: {
name: 'custom',
templateAttribute: [{
type: "string",
attribute: "material"
}, {
type: "string",
attribute: "soles"
}, {
type: "string",
attribute: "size"
}]
}
}];
// add menu item
$scope.addItem = function(list, item) {
item = {};
list.push(angular.copy(item));
};
// remove menu item
$scope.removeItem = function(list, index) {
list.splice(index, 1);
};
}
angular
.module('app', [])
.controller("ExampleCtrl", ExampleCtrl)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.10/angular.min.js"></script>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="ExampleCtrl">
<h3>How to fix this</h3>
<p>My problem is when I fill out one form above and click on the add button, it will display a new form, but that form always has the same value. Demo:</p>
<label>Category:
<select ng-model="product.category" ng-options="category as category.name for category in categories"></select>
</label>
<br/>
<br />
<table class="table" ng-repeat="attr in product.category.templateAttribute">
<thead>
<tr>
<th colspan="4">{{attr.attribute}}</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input value="{{attr.attribute}}" />
</td>
<td>
<input placeholder="name" ng-model="product.attributes[attr.attribute].name" />
</td>
<td>
<input placeholder="additional price" ng-model="product.attributes[attr.attribute].additionalPrice" />
</td>
<td rowspan="2">
<button type="button" ng-click="addItem(product.category.templateAttribute, attr)">
add
</button>
</td>
</tr>
<tr>
<td colspan="3">
<input type="file" class="form-control" ng-model="product.attributes[attr.attribute].file" />
</td>
</tr>
</tbody>
</table>
</body>
</html>
Codepen demo

How to use submit button to search the record in a table?

Here is my index.html page
------index.html-------
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.0-beta.6" data-semver="1.4.0-beta.6"
src="https://code.angularjs.org/1.4.0-beta.6/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="PeopleCtrl"> <input type="text"
name="search1" >
<input type="submit" ng-model="search1" value="search"
ng-click="checkAll"> <table border="1" ng-init="ageToShow=(people|
underTwenty: 20).length >= 1">
<tr name="search1" > <th>Id</th> <th>Name</th> <th ng-show="ageToShow"
ng-if="!ageToShow">Age</th> </tr> <tr ng-repeat="person in
people|filter: search" ng-show="person.age>20" >
<td><span>{{person.id}}</span> </td> <td><span>{{person.name}}</span>
</td> <td ng-show="!ageToShow"><span>{{person.age}}</span> </td> </tr>
</table>
</div> </body> </html>
What i need is to use submit button to search the record .... And here is my script.js file...
--------script.js--------
// Code goes here
var myApp = angular.module('myApp', []);
myApp.controller('PeopleCtrl', function($scope,$filter) {
$scope.people = ([{
id: 1,
name: "Peter",
age: 22 }, {
id: 2,
name: "David",
age: 12 }, {
id: 3,
name: "Anil",
age: 32 }, {
id: 4,
name: "Chean",
age: 22 }, {
id: 5,
name: "Niladri",
age: 18 }
]);
$scope.people3 = $scope.people;
$scope.$watch('search1', function(val)
{
$scope.people = $filter('filter')($scope.people3, val);
});
}); myApp.filter('underTwenty', function() {
return function(values, limit) {
var returnValue = [];
angular.forEach(values, function(val, ind) {
if (val.age < limit)
returnValue.push(val);
}); return returnValue; }; });
And here goes my coding in plunker: http://plnkr.co/edit/?p=preview
Only for filtering if you are planning to do submit the form, then I'll suggest you to don't prefer form submit.
Form getting the same requirement done I'd create one dummy field for search text-box & then I'd assign that would to search model which we using for filter on click of search ng-click="search = search1"
HTML
<input type="text" name="search1" ng-model="search1"/>
<input type="button" value="search" ng-click="search = search1">
<table border="1" ng-init="ageToShow=(people| underTwenty: 20).length >= 1">
<tr name="search1">
<th>Id</th>
<th>Name</th>
<th ng-show="ageToShow" ng-if="!ageToShow">Age</th>
</tr>
<tr ng-repeat="person in people|filter: search" ng-show="person.age>20">
<td><span>{{person.id}}</span>
</td>
<td><span>{{person.name}}</span>
</td>
<td ng-show="!ageToShow"><span>{{person.age}}</span>
</td>
</tr>
</table>
& Do remove the watch from search1 variable. So the filtering will not occur on change of search1
Working Plunkr

Adding a select list to knockout VM not populating selects value

I am trying to learn a little bit of knockout.js so I am running through the examples on the website in particular the contact example. (Knockout Contacts Editor)
I am trying to extend this example by adding a select list with a property of 'ContactType'
ContactType is a basic list containing 2 objects.
I have created a fork of the example and extended it slightly My Extended Example fiddle
var initialData = {
"names": [{
firstName: "Danny",
lastName: "LaRusso",
contactTypeId: 1,
phones: [{
type: "Mobile",
number: "(555) 121-2121"
}, {
type: "Home",
number: "(555) 123-4567"
}]
}, {
firstName: "Sensei",
lastName: "Miyagi",
contactTypeId: 2,
phones: [{
type: "Mobile",
number: "(555) 444-2222"
}, {
type: "Home",
number: "(555) 999-1212"
}]
}],
"contactTypes": [{
"id": 1,
"type": "Family"
}, {
"id": 2,
"type": "Friend"
}]
}
var ContactsModel = function (contacts) {
var self = this;
self.contactTypes = ko.observableArray(ko.utils.arrayMap(contacts.contactTypes,
function (contactType) {
return {
id: contactType.id,
type: contactType.type
};
}));
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts.names, function (contact) {
return {
firstName: contact.firstName,
lastName: contact.lastName,
phones: ko.observableArray(contact.phones),
contactTypeId: ko.observable(contact.contactTypeId)
};
}));
self.addContact = function () {
self.contacts.push({
firstName: "",
lastName: "",
phones: ko.observableArray(),
contactTypeId: ko.observable()
});
};
self.removeContact = function (contact) {
self.contacts.remove(contact);
};
self.addPhone = function (contact) {
contact.phones.push({
type: "",
number: ""
});
};
self.removePhone = function (phone) {
$.each(self.contacts(), function () {
this.phones.remove(phone)
})
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
};
self.lastSavedJson = ko.observable("")
};
ko.applyBindings(new ContactsModel(initialData));
HTML
<div class='liveExample'>
<h2>Contacts</h2>
<div id='contactsList'>
<table class='contactsEditor'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Contact Type</th>
<th>Phone numbers</th>
</tr>
<tbody data-bind="foreach: contacts">
<tr>
<td>
<input data-bind='value: firstName' />
<div><a href='#' data-bind='click: $root.removeContact'>Delete</a>
</div>
</td>
<td>
<input data-bind='value: lastName' />
</td>
<td>
<select class="form-control" data-bind="options: $root.contactTypes,
optionsText: 'type',
optionsValue:'id',
value:'contactTypeId',
optionsCaption: 'Please Select...'"></select>
</td>
<td>
<table>
<tbody data-bind="foreach: phones">
<tr>
<td>
<input data-bind='value: type' />
</td>
<td>
<input data-bind='value: number' />
</td>
<td><a href='#' data-bind='click: $root.removePhone'>Delete</a>
</td>
</tr>
</tbody>
</table> <a href='#' data-bind='click: $root.addPhone'>Add number</a>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<button data-bind='click: addContact'>Add a contact</button>
<button data-bind='click: save, enable: contacts().length > 0'>Save to JSON</button>
</p>
<textarea data-bind='value: lastSavedJson' rows='5' cols='60' disabled='disabled'></textarea>
</div>
I have 2 problems which I am not sure what I am doing wrong with.
When the page is loaded the select list is not displaying the correct value. Instead its just displaying the 'Please Select' value
When I try save the record the selected value from the select list is not saved.
Am I doing something obviously wrong here?
The issue was you were setting the value binding incorrectly. Instead of value: 'contactTypeId' when it should just be value: contactTypeId without the quotations.
<select class="form-control" data-bind="options: $root.contactTypes,
optionsText: 'type',
optionsValue: 'id',
value: contactTypeId,
optionsCaption: 'Please Select...'">
</select>
Also for the save function it's better to use use knockouts ko.toJSON instead of JSON.stringify(ko.toJS
self.save = function () {
self.lastSavedJson(ko.toJSON(self.contacts), null, 2);
};

Angular app throws error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
My code is like this
<div ng-app='myApp' ng-controller="MainCtrl">
<div ng-repeat="prdElement in pacakageElement track by $index" class="package-grid">
<div style="border: 1px solid; padding-bottom: 10px; padding-top: 10px">
<input placeholder="Product Code" />
<input placeholder="Dimension" />
</div>
<table class="hovertable">
<thead>
<tr>
<th>Line #</th>
<th>ITCLS</th>
<th>Item #</th>
<th>Line Quantity#</th>
<th>Ship Quantity</th>
<th>PickQuantity</th>
<th>Quantity in Plt</th>
<th>Allready Packed</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in prdElement.Data" ng-init="data.newquantity = data.quantity">
<td>{{data.itemId}}</td>
<td>{{data.itcls}}</td>
<td>{{data.itemId}}</td>
<td>Line Quantity#</td>
<td>Ship Quantity</td>
<td>PickQuantity</td>
<td>
<input type="text" ng-model="data.newquantity" placeholder="Quantity" required=required />
</td>
<td>Allready Packed</td>
</tr>
<tr>
<td width="100%" colspan="4">
<button ng-show="prdElement.show" ng-click="newPackageItem( prdElement,$event)">Next Pallet</button>
</td>
<td width="100%" colspan="4">
<button ng-show="prdElement.show">Remove Pallet</button>
</td>
</tr>
</tbody>
</table>
</div>
(function () {
angular.module('myApp', []).controller('MainCtrl', function ($scope) {
var counter = 0;
$scope.pacakageElement = [{
name: counter,
show: true,
Data: [{
name: 'item 1',
itemId: '284307',
itemCode: '',
description: 'Bicycle parts - frame',
quantity: '100',
handlingUnit: 'CTN',
weight: '613.04',
class: '',
lenght: '102',
width: '42',
height: '61',
flag: 'P'
}, {
name: 'item 2',
itemId: '284308',
itemCode: '',
description: 'Bicycle parts - fork',
quantity: '200',
handlingUnit: 'CTN',
weight: '242.99',
class: '',
lenght: '75',
width: '34',
height: '18',
flag: 'P'
}]
}];
$scope.newPackageItem = function (packageElement, $event) {
var npackageElement = {};
angular.copy(packageElement, npackageElement);
counter++;
packageElement.show = false;
npackageElement.name = counter;
angular.forEach(npackageElement.Data, function (row) {
if (row.quantity != row.newquantity || row.quantity != 0) {
row.quantity = row.quantity - row.newquantity;
}
});
$scope.packageElement.push(npackageElement);
};
});
}());
Here I am trying to duplicate my first dataset and do some calculations on it. Everything works fine except function newPackageItem. this function alone throws error
TypeError: Cannot read property 'push' of undefined
at Scope.$scope.newPackageItem
Fiddle
You misspelled the property "packageElement" as "pacakageElement". Change all instances to use "packageElement" and it should work.

Categories

Resources