Data is retrieved in my AngularJS app via $http.get and rendered like this:
# Angular
app.controller('MainCtrl', function ($scope, $http) {
$scope.cart = {};
$scope.cart.retrieve = function() {
// make $http to retrieve data
.success(function(results) {
$scope.cart.contents = results
});
};
$scope.cart.update = function(itemId) {
// make $http request to update cart
}
});
# HTML
<table ng-init="cart.retrieve()">
<tbody>
<tr ng-repeat="item in cart.contents">
<td>{{ item.price }}</td>
// item quantity input field
<td><input type="number" name="quantity" on-change="cart.update(item.id)"
ng-model="item.qty"></td>
<td>{{ item.price * item.qty }}</td>
</tr>
</tbody>
</table>
When the item quantity is changed in input field, the function that passes item id fires: $scope.cart.update = function(itemId) { ... } . How do I retrieve this new quanity value for this particular item that triggered on-change event. Is there something in angular like this I can use inside the function?
You can pass item to your cart.update function:
on-change="cart.update(item)"
And then use the qty of this item
$scope.cart.update = function(item) {
// do whatever you want with
// item.qty
}
Related
I am trying to update quantity number of individual items in a table whenever the user clicks the item in another table.
For example, I have list of all items in Table A
<tr ng-repeat="item in items">
<td>{{item.fid}}</td>
<td{{ item.fname }}</td>
<td>{{ item.calorie }}</td>
<td>{{ item.protein }}</td>
<td>{{ item.carb }}</td>
<td>{{ item.fat }}</td>
<td><button ng-click=additem(values)>Add</button>
<tr>
Now when the user clicks this Add button, the selected item gets added to another table (Table B).
I have disabled duplicates in Table B and want that if the user is repeatedly adding same item then the quantity of the item in Table B should increase.
Table B
<tr ng-repeat="sitem in sitems>
<td>{{sitem.fname}}</td>
<td>{{sitem.calorie}}</td>
<td>{{sitem.protein}}</td>
<td>{{sitem.carb}}</td>
<td>{{sitem.fat}}</td>
<td>*</td>
<td><button ng-click="removeItem(values)">Remove</button></td>
</tr>
is the one where i want the increased quantity to be shown.
I have tried using "this" keyword but didn't worked, I am new to angular so i don't know what all are my options and got mixed up.
You have to keep track of two separate array to accomplish this.
This is the code snippet: `
$scope.additem = function(item) {
var index = $scope.sitems.indexOf(item);
if (index === -1) {
item.quantity = 1;
$scope.sitems.push(item);
return;
}
item.quantity++;
$scope.sitems[index] = item;
};
`
Complete Working fiddle: https://jsfiddle.net/nbakliwal18/4kbo7Lfo/2/
Also you check for quantity before adding.
You can simply pass item to the function addItem() :
<td><button ng-click=addItem(item)>Add</button>
and push this item to your array sitems in your function :
$scope.addItem = function(item) {
$scope.sitems.push(item);
}
A workaround for the duplicates in ng-repeat is to add track by $index to it :
<tr ng-repeat="sitem in sitems track by $index">
Update 1:
Updated my answer with working example in Plunker
Update 2:
Here is an example with lodash for quantity Plunker
I have a static HTML table in which have 2 column one is for employeeID and other is for Employee Name regarding every entry a asp:button appears generated. I want on the click of button it gives me employeeID.
<div ng-app="myApp" ng-controller="myCtrl">
<table border="1" width="100%">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>
<tr ng-repeat="detail in details" align="center">
<td>{{ detail.EmployeeID }}</td>
<td>{{ detail.EmployeeName }}</td>
<td>
<asp:Button ID="btnDelete" Text="Delete Request" CommandArgument="{{detail.EmployeeID}}" runat="server" OnClick="btnDelete_Click"/>
</td>
</tr>
</table>
Below is script to render value form XML in the table
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$http.get('myDB.xml')
.then(function (response) {
var x2js = new X2JS();
//$scope.details = response.data.UserDetail;
$scope.details = [];
/*setting up the response*/
var data = x2js.xml_str2json(response.data);
$scope.details = data.UserDetail.Detail;
});
$scope.removerequest = function (row) {
$scope.details.splice($scope.delete.indexOf(row), 1);
}
});
XMl
<UserDetail>
<Detail>
<EmployeeID>997857</EmployeeID>
<EmployeeName>Aakash</EmployeeName>
</Detail>
<Detail>
<EmployeeID>999786</EmployeeID>
<EmployeeName>Amit</EmployeeName>
</Detail>
</UserDetail>
Button click code
protected void btnDelete_Click(object sender, EventArgs e)
{
string id=btnApprove.CommandArgument;
Response.Write(id);
var xDoc = XDocument.Load(#"D:\test\myDB.xml");
xDoc.Descendants("Detail")
.Elements("EmployeeID")
.Where(x => x.Value == id)
.Remove();
xDoc.Save(#"D:\test\myDB.xml");
}
how to get td value in command argument form angularJS bind element
you can pass the employeeID like so, ng-click= btnDelete_Click( detail.EmployeeID ) in your button. this takes the scope variable defined by the ng-repeat and passes it as an argument for the function BtnDelete_Click()
So we're developing this angular app with a firebase backend. I am having trouble with this particular function we're implementing. Basically what it does is every time a different option is selected, the showData() function fires to retrieve the relevant data from firebase (and it works). The problem is that the ng-repeat only updates on the first selection change. Successive selection changes are not reflected in the ng-repeat (although the data is retrieved and thus, the model changed).
View:
<div class="container" ng-controller="dataController">
...
<select ng-model="selectedOption" ng-change="showData()">
<option ng-repeat="entry in transactions" ng-value="entry.serial">{{ entry.serial }}</option>
</select>
</div>
<div class="col-md-9">
<table class="table table-hover table-striped table-condensed">
...
<tbody>
<tr ng-repeat="entry in dataHistory">
<td>{{ entry.id }}</td>
<td>{{ entry.timestamp | date:"yyyy MMM dd 'at' h:mm:ssa" }}</td>
<td>{{ entry.amount }}</td>
</tr>
</tbody>
</table>
</div>
Controller:
...
.controller('dataController', ['$scope', '$firebaseArray', function($scope, $firebaseArray) {
...
$scope.showData = function() {
$scope.dataHistory = [];
transfersRef.orderByChild('serial').equalTo($scope.selectedOption).on('child_added', function(snap) {
transactionsRef.orderByKey().equalTo(snap.val().transactionID).on('child_added', function(data) {
var entry = {};
entry = data.val();
entry.id = data.key();
usersRef.child(entry.fromUserId).child('name').once('value', function(nameSnap) { entry.fromUsername = nameSnap.val(); });
usersRef.child(entry.toUserId).child('name').once('value', function(nameSnap) { entry.toUsername = nameSnap.val(); });
console.log('entry: \n' + entry);
$scope.dataHistory.push(entry);
});
});
};
}])
...
Try applying $scope.$apply() after $scope.dataHistory.push(entry); in your code.
This is because your array updating code maybe outside the angular digest cycle.
I have a problem with my custom filter function in angular.
This is the filter function:
.filter('itemFilter', function($rootScope) {
return function(input) {
var filtered = [];
angular.forEach(input, function(item) {
if(item.user_id === $rootScope.userData._id && item.active === true){
filtered.push(item);
}
});
//console.log(filtered);
return filtered;
}
});
The filter does what it should do, but when i want to push a new Object in the item Array, the filter does not get the new Object. The new Item is pushed in the array correctly, though.
This is where the item is pushed in the DB and in the rootScope. The function is located inside a factory and called in the controller.
Function in the factory:
var addItem = function(item){
$http.post("http://localhost:3333/items", item)
.success(function (response) {
$rootScope.items.push(item);
$log.debug(response);
})
.error(function (err){
$log.error("item was not added: "+err);
});
};
Call of the function in the controller:
$scope.itemObj = {"user_id": $rootScope.userData._id, "group_id": $rootScope.userData.group_id};
$scope.addItem = function() {
console.log($scope.itemObj);
dataFactory.addItem($scope.itemObj);
$modalInstance.close();
$scope.itemObj = {"user_id": $rootScope.userData._id, "group_id": $rootScope.userData.group_id};
};
The whole array with all items is located in the rootScope.
This is the part where I call the ng-repeat:
<tbody ng-repeat="item in items | itemFilter | filter: qry | orderBy: '-created'">
<tr popover="{{item.description}}" popover-trigger="mouseenter">
<td>{{item.amount}}</td>
<td>{{item.name}}</td>
<td>{{item.price | currency:"EUR€ "}}</td>
<td>{{item.list}}</td>
<td ng-controller="EditItemCtrl"><a class="btn btn-default" ng-click="open(item)">Edit</a></td>
<td><a class="btn btn-danger" ng-click="deleteItem(item)">Delete</a></td>
<td ng-controller="BoughtItemCtrl">
<a class="btn btn-success" ng-click="open(item)">Bought</a>
</td>
<td>
<p ng-show="!item.active">NO</p>
<p ng-show="item.active">YES</p>
</td>
</tr></tbody>
Is there any way to tell the filter, that a new item has been added to the array? After reloading the page, everything works fine, because the filter gets the whole items array.
I think i fixed the problem.
Instead of pushing the 'item' into the array I am now pushing the 'response' into it.
var addItem = function(item){
$http.post("http://localhost:3333/items", item)
.success(function (response) {
$rootScope.items.push(response);
$log.debug(response);
})
.error(function (err){
$log.error("item was not added: "+err);
});
};
The pushed response has an now '_id'-value (which is generated by the MonogDB). I am not sure if the missing id was the problem.
Maybe you have an answer for that.
Thanks anyway for the quick responses.
I have this code:
$scope.search = function() {
$scope.results = ejs.Request()
.query(ejs.TermQuery("amount", 10)).size(10).from(0)
.doSearch();
console.log($scope.results.v);
};
and :
<tr id="tr" ng-repeat="record in results.hits.hits" repeat-done="reload_scroll()">
<td><input type="checkbox" ng-model="record._source.checked"/></td>
<td>{{ record._source.id }}</td>
</tr>
and it work properly. But I want to have access to $scope.results in js code but when I write:
$scope.search = function() {
$scope.results = ejs.Request()
.query(ejs.TermQuery("amount", 10)).size(10).from(0)
.doSearch();
console.log($scope.results.$$v);
};
but it print undefined it console, what should I use instead $$v?
Thanks.
Since it is a async call you would get the results in a callback. Something like
ejs.Request()
.query(ejs.TermQuery("amount", 10)).size(10).from(0)
.doSearch().then(function(data) {
console.log(data);
});