I have developed simple angular-firebase application which provide basic CRUD functionality.
json format in firebase
{
"-J0wuZ_J8P1EO5g4Xfw6" : {
"contact" : "56231545",
"company" : "info",
"city" : "limbdi",
"name" : "priya"
},
"-J0wrhrtgFvIdyMcSL0x" : {
"contact" : "65325422",
"company" : "rilance",
"city" : "jamnagar",
"name" : "pihu"
}
}
angular-code for listing all data in html page
<table class='table table-hover'>
<tr>
<th>Name</th>
<th>City</th>
<th>Company</th>
<th>Contact</th>
<th></th>
</tr>
<tr ng-repeat="item in employee">
<td>{{item.name}}</td>
<td>{{item.city}}</td>
<td>{{item.company}}</td>
<td>{{item.contact}}</td>
<td><button class='btn btn-warning btn-mini' ng-click='delemp(employee[$index])'>X</button></td>
</tr>
</table>
when someone click on button it fire delemp function which take employee's current index as argument.
var myapp = angular.module('myapp',['firebase']);
myapp.controller('MyCtrl', ['$scope', 'angularFireCollection',
function MyCtrl($scope, angularFireCollection) {
$scope.delemp=function($current_emp){
alert($current_emp.name);
};
}
]);
this alert box contain current employee's name. I want to delete current row of employee. but I don't know how to use remove() method of firebase. I have visited documentation of firebase so I got bellow code which is working nice.
var current = new Firebase('https://myurl/employee/-J48go0dwY5M3jAC34Op');
current.onDisconnect().remove();
but I want to make it dynamically so how can I get parent id of current node like -J48go0dwY5M3jAC34Op ?
please help me to figure out small issue.
instead of passing the object, you could just pass the id into your delete function.
<li ng-repeat="(key,item) in list">
<button ng-click="deleteItem(key)">delete</button> {{item.name}}
</li>
$scope.deleteItem = function(id){
var itemRef = new Firebase(url + '/' + id);
itemRef.remove();
}
edit:
this also works
<div ng-repeat="item in list">
<button ng-click="writeID(item)">log id</button>{{item.$id}} {{item}}<hr>
</div>
$scope.writeID = function(o){
console.log(o.$id);
}
If it's a firebaseArray, you can also do it this way:
$scope.deleteItem = function(item){
employee.$remove(item);
}
Just pass the item you want to remove from the object.
Note: It won't work for firebaseObjects.
Useful sources:
https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-firebasearray-removerecordorindex
https://gist.github.com/anantn/4325082
Related
Here is my scenario, I have rows of data in a table with ContractId and CustomerName values from a dataset. I made the ContractId value a link when the user clicks they would be redirected to another page with the CustomerName value from that row. Now I'm struggling how to pass that value and access that value in another controller.
So I have searched the internet and learned a lot of methods how to pass values from a controller to another like services, $stateparams, $rootscopes and the $broadcast,$emit methods. I have chosen the $broadcast method since my controllers are in a hierarchy and I just need my child controller to pass the CustomerName value to the parent controller. I have tried placing a ng-click within my anchor tag and created a save event and passed my CustomerName value but I'm getting a Error: $parse:syntax Syntax Error.
<div class="container" data-ng-controller="contractCtrl">
<div class="card" ng-controller="contractlistCtrl">
<form class="form-horizontal" name="formBank">
<div class="card-header">
<h2>Contract List</h2>
</div>
<div class="card-body card-padding">
<div class="card-body">
<div class="table-responsive">
<table ng-table="tableFilter" class="table table-striped table-vmiddle" show-filter="true">
<tr ng-repeat="contractDetails in $data">
<td data-title="'Contract No'" >
<a ng-href="#/admin/contract/first" ng-click="save({{ contractDetails.CustomerName }})">{{ contractDetails.ContractId }}</a>
</td>
<td data-title="'Customer'" >
{{ contractDetails.CustomerName }}
</td>
<td data-title="'Sales Agent'">
{{ contractDetails.SalesAgentName }}
</td>
<td data-title="'Item Type'">
{{ contractDetails.ItemTypeName}}
</td>
<td data-title="'Item Id'" >
{{ contractDetails.ItemId }}
</td>
<td data-title="'Item Name'" >
{{ contractDetails.Model }}
</td>
<td data-title="'Payment Terms'">
{{ contractDetails.TermName }}
</td>
<td data-title="'Status'" >
{{ contractDetails.Status}}
</td>
</tr>
</table>
</div>
</div>
<!--<button type="submit" class="btn btn-primary btn-sm m-t-20" ng-click="generateReport(ReportId,FromDate,ToDate)">Generate</button>-->
</div>
</form>
</div>
</div>
Here is my child controller
materialAdmin
.controller('contractlistCtrl', function ($rootScope, $scope, ngTableParams, $filter, contractService, $state, $timeout, $stateParams, $window) {
contractService.getListData().then(function (result) {
$scope.insertIntoDataTable(result);
});
$scope.insertIntoDataTable = function (resultData) {
$scope.data = (resultData !== null) ? resultData : [];
$scope.length = $scope.data.length;
//Filtering
$scope.tableFilter = new ngTableParams({
page: 1,
count: 10
}, {
total: $scope.data.length,
getData: function ($defer, params) {
var orderedData = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
var slice = orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count());
this.ContractId = slice;
this.CustomerName = slice;
this.SalesAgentName = slice;
this.ItemTypeName = slice;
this.ItemId = slice;
this.Model = slice;
this.TermName = slice;
this.Status = slice;
params.total(orderedData.length);
$defer.resolve(this.ContractId, this.CustomerName, this.SalesAgentName, this.ItemTypeName, this.ItemId, this.Model, this.TermName, this.Status);
}
})
}
$scope.save = function (data) {
$scope.$broadcast("SendDown", data);
}
})
Then I have this piece of code in my parent controller to receive the data
$scope.$on("SendDown", function (data) {
$scope.customerSelected = data;
});
All I'm trying to do is to pass a value to another controller when the anchor tag is clicked.
UPDATE
I have taken the advise of using $stateparams instead of broadcast and I got it working. I followed what was stated and added this code on another js file to set the state.
.state('contract.contract.contractlist', {
url: '/first/:customer',
templateUrl: 'views/contract_first.html',
controller: function ($stateParams) {
console.log($stateParams);
}
})
There are some syntax errors in your code. First of all here:
<tr ng-repeat="contractDetails in $data">
$data should be data.
Also, here there is no need of {{ }} inside ng-click :
ng-click="save(contractDetails.CustomerName)"
But, in general you don't need ng-click and you don't need $broadcast.
You just need to pass the value as parameter on redirection. One way to achieve that is:
ng-href="#/admin/contract/first/{{contractDetails.ContractId}}"
(It is better to send id instead of name)
And then in new state you can retrieve the value (with $stateParams if you are using ui-router).
EDIT: How to pass transition parameter without showing in url
You can use ui-sref directive (part of ui-router) to send the parameter to new state like this:
ui-sref="contract.contract.contractlist({customer: contractDetails.CustomerName})"
In state declaration remove the parameter from the url and add params field:
.state('contract.contract.contractlist', {
url: '/first',
templateUrl: 'views/contract_first.html',
params: {
customer: null
}
})
For documentation check here: https://github.com/angular-ui/ui-router
I've started looking at AngularJS a few hours ago so I'm settling into how things work. As part of a basic example, I'm trying to figure out how I switch between displayed data in a table.
At the moment, I've got the following as my basic app;
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
</head>
<body>
<div ng-app="applicationMain" ng-controller="controllers.app.main">
<table>
<tr ng-repeat="item in items">
<button>Toggle</button>
<td>{{item.name}}<td>
</tr>
</table>
</div>
</body>
<script>
var controllers = {
app : {
main : function($scope){
var s = $scope;
s.items = [
{
name : "Pizza",
price : 100
},
{
name : "Burger",
price : 45
},
{
name : "Kebab",
price : 85
}
];
}
}
}
var app = angular.module("applicationMain", []);
app.controller('controllers.app.main', controllers.app.main);
</script>
</html>
Fairly simple. Scoped array of objects with name and price fields, where the name of each is displayed in a table using ng-repeat
What I'd like to do is when I click the Toggle button, it switches between displaying the data of item.name to displaying data of item.price.
Is this something that can be done within the angular expression of the <TD> tags, or would a function be the way to go?
If I was using regular old JS for example, I might do something like this;
var activeField = item.name;
if (activeField == item.name){
activeField = item.price
} else {
activeField = item.name
}
However, I tried something similar by creating a 'switchField' function in my controller, but Angular reports that 'item is not defined' (essentially a scoping issue) even when defining it at $scope.item.price and $scope.item.name respectively.
You can do something like this, using ngClick, ngShow and ngHide:
<table>
<tr ng-repeat="item in items">
<button ng-click="toggleIt()">Toggle</button>
<td ng-show="toggle">{{item.name}}<td>
<td ng-hide="toggle">{{item.price}}<td>
</tr>
</table>
And add this to the controller:
s.toggle = true;
s.toggleIt = function() {
s.toggle = !s.toggle;
}
First of all I am very new in Angular JS.
I have a list of items and by clicking on each one, it should be added to the table. The items are stored in a json file.
If the click event repeated several times the counter input which is located on the table must increases.
<ul class="list-inline" >
<li ng-repeat="food in foods" class="food_list">
<img class="img-box" src="images/{{ food.food_photo }}" ng-click = 'addRow(food)'><br/><span>{{food.food_name}}</span>
</li>
</ul>
<table class="table" id="table-right">
<tr>
<th>Item Name</th>
<th>Quantity</th>
<th>Price</th>
<th class="hidden-print">Delete</th>
</tr>
<tr ng-repeat="row in rows">
<td>{{row.food_name}}</td>
<td><input type="number" class="form-control" ng-model="row.food_count"></td>
<td>{{row.food_cost}}</td>
<td class="hidden-print"><button class="btn btn-info hidden-print" data-ng-click="removeRow($index)">Remove</button></td>
</tr>
app = angular.module('app',[]);
app.controller('MyCtrl', ['$scope','$http', function($scope, $http){
$scope.rows = [];
$scope.addRow = function(obj) {
$scope.foodname = obj.id;
$scope.foodprice = obj.price;
$scope.rows.push(obj);
$scope.counter++;
}
}]);
Could you please help me? Thank You.
First you have to understand that food_count property of a row object is the variable that should be updated on repetitive clicks. Updating any other $scope variables won't change row specific data because your view is bound to $scope.rows object.
Your addRow function should look like this.
$scope.addRow = function(obj) {
if($scope.rows.indexOf(obj) >= 0){ // if this obj already exist
$scope.rows[$scope.rows.indexOf(obj)].food_count++;
}
else
$scope.rows.push(obj);
}
Then the objects of $scope.foods should have a property called food_count to display.
$scope.foods = [
{food_name:'Jani',food_cost:'10', food_count:0},
{food_name:'Hege',food_cost:'8',food_count:0},
{food_name:'Kai',food_cost:'5',food_count:0}]
solution
I downloaded an Angular demo app to learn and work my way through Angular basics. I am having issue with applying a filter and sort to a data table. I made it by referring some examples and not sure if it is correct.
My table is :
<div class="widget-content" ng-controller="getAllBenchersController">
<table ng-table="talentPoolList" show-filter="true" class="table table-striped table-bordered">
<tr ng-repeat="employee in data | filter: testFilter">
<td data-title="'#'">{{$index + 1}}</td>
<td data-title="'Employee ID'" sortable="'empno'" filter="{ 'empno': 'text' }">
{{employee.employee.employeeNo}}
</td>
<td data-title="'First Name'" sortable="'employee.employee.firstName'" filter="{ 'employee.employee.firstName': 'text' }">
{{employee.employee.firstName}}
</td>
</tr>
</table>
</div>
Controller :
myApp.controller('getAllBenchersController', ['$scope', 'employeeTalentPoolServices', function ($scope, employeeTalentPoolServices) {
employeeTalentPoolServices.getAllBenchers().then(function (result) {
$scope.data = result.data;
$scope.testFilter = function (item) {
return (item.state.state.toLowerCase() === 'available' || item.state.state.toLowerCase() === 'blocked');
}
});
I have no clue how it works. Can anyone explain and provide a solution to fix this issue?
Thanks in advance
So to explain your demo example I've created a similar example to make you understand what's happening in your question.
We have a employees data with different statuses so when I want to display the list of employees I just want show 'fair' and 'good' so I've written a filter function passed to filter directive to tell what items should be displayed from the list.
If you observe the function it takes every item from list and checks for status to match the desired statuses for displaying.
Check out the demo for the same, hope this gives you a clear understanding on what's happening in your Demo app.
var app = angular.module('app',[]);
app.controller('getAllBenchersController',function($scope,$filter){
$scope.data = {employee:[
{'no':1,'name':'max','status':'bad'},
{'no':2,'name':'fox','status':'good'},
{'no':3,'name':'juno','status':'bad'},
{'no':4,'name':'pet','status':'fair'},
{'no':5,'name':'xyz','status':'good'},
{'no':6,'name':'shit','status':'bad'},
{'no':7,'name':'doggy','status':'fair'},
{'no':8,'name':'hmmm','status':'bad'}
]}
//this test filter is a function which allows me to decide which data should be displayed in this case I've used 'fair' & 'good' status employees to be displayed...
$scope.testFilter = function (item) {
return (item.status.toLowerCase() === 'good' || item.status.toLowerCase() === 'fair');
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" class="widget-content" ng-controller="getAllBenchersController">
<table>
<tr ng-repeat="emp in data.employee | filter: testFilter">
<td>{{$index+1}} </td>
<td> {{emp.no}}</td>
<td>{{emp.name}} </td>
</tr>
</table>
</div>
I want to assign and retrieve the whole object to ng-value on ng-repeat. And when I select a row of table using radio button, I want to get the object of the selected row.
HTML:
<button ng-click="save()">Save</button>
<table id="remark-table">
<thead>
<tr>
<th>Name</th>
<th>Remarks</th>
<th>Indicator</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in remarks track by data.id">
<td>{{data.name}}</td>
<td>{{data.remarks}}</td>
<td><input type="radio" name="indicator" ng-model=data ng-value=data></td>
</tr>
</tbody>
</table>
JS:
$scope.remarks = [{
name : 'John',
remarks : 'Remark 1'
},
{
name : 'Tom',
remarks : 'Remark 2'
},
{
name : 'Jerry',
remarks : 'Remark 3'
}];
$scope.save = function() {
var remarks = angular.element('#remark-table tbody tr td').find('input[name="indicator"]:checked').val();
}
remarks is returned as [object Object]
Fiddle is not opening at the moment. Hence posted the code here. Kindly help with this. Thanks in advance!
Try it like this in the html:
<input type="radio" name="indicator" ng-model="$parent.data" ng-value="data">
And in the controller you can get it like this:
$scope.save = function() {
var remarks = $scope.data;
}
Didnt actually tested, so try it out and see if it works...