Get data from row when clicked and display to editable dialog box - javascript

I'm trying to use Angularjs to get data from a row in a table when it is clicked and display it in an editable dialog box. How can I do this? Here's what I have so far:
<table>
<thead>
<tr>
<th>ID No.</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Gender</th>
<th>Time</th>
<th>Date</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td><a class="click">{{walkin_member.id}}</a></td>
<td>{{walkin_member.firstname}}</td>
<td>{{walkin_member.lastname}}</td>
<td>{{walkin_member.gender}}</td>
<td>{{walkin_member.time}}</td>
<td>{{walkin_member.datestamp}}</td>
<td>{{walkin_member.type}}</td>
</tr>
</tbody>
</table>
This is my dialog box markup:
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" value="{{walkin_member.firstname}}"><br/>
Lastname <input type="text" value="{{walkin_member.lastname}}"><br/>
Gender <input type="text" value="{{walkin_member.gender}}"><br/>
Type <input type="text" value="{{walkin_member.type}}"><br/>
</div>
<div id="dlg-footer">
<button onclick="dlgUpdate()">Update</button>
<button onclick="dlgExit()">Exit</button>
</div>
</div>
Here's my controller:
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
the dialog box is hidden, it will just show if the function is triggerd onclick
here's my javascript.
function showDialog(){
var whitebg = document.getElementById("white-background");
var dlg = document.getElementById("dlgbox");
whitebg.style.display = "block";
dlg.style.display = "block";
var winWidth = window.innerWidth;
dlg.style.left = (winWidth/2) - 480/2 + "px";
dlg.style.top = "150px";
}

Add an ng-click event to the anchor tag in each row and pass the current member to the method.
<tr ng-repeat="walkin_member in data | filter:searchFilter">
<td>
<a class="click" href="#"
ng-click="showInEdit(walkin_member)">{{walkin_member.id}}</a>
</td>
</tr>
Now in your controller, Add a new property to hold the selected member and a method called showInEdit()
myApp.controller('loglistController', ['$scope', '$http', function ($scope, $http) {
$scope.data=[];
$scope.selectedMember={ firstname:"",lastname:"",gender:"",type:"" }; //new property
$http.get("../php/loglistajax.php")
.success(function(data){
$scope.data = data;
})
.error(function() {
$scope.data = "error in fetching data";
});
$scope.showInEdit=function(member){
$scope.selectedMember = member;
};
}]);
And in your model dialog, you will use the selectedMember property.
<div id="dlgbox">
<div id="dlg-header">Information</div>
<div id="dlg-body">
Firstname <input type="text" ng-model="selectedMember.firstname" />
</div>
</div>

Related

Angular.js - Redirection is cleaning my $scope(?)

I have an $ngController that is being used in two views. The first view has an <table> with ng-repeat that lists all my data from the db.
I get the selected object form the table by using get($index) and set it to a $scope variable.
The problem is that when i cannot use this same $scope variable on the other view, because its value is undefined. Both views share the same ng-controller.
My Question is: is the redirection cleaning my $scope? Is there any way i can share this data between pages since my application isn't single page?
Things i tried:
1 - Share data through a factory
2 - Using $rootScope
First View - Table with ng-repeat
<table class="table table-striped">
<thead>
<tr>
<th>CNPJ</th>
<th>Razão Social</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="company in companies | filter:{companyName:searchString}">
<td> {{ company.cnpj }}</td>
<td> {{ company.companyName }}</td>
<td>
Visualizar
<button type="button" class="btn btn-warning btn-xs">Editar</button>
<button type="button" class="btn btn-danger btn-xs">Deletar</button>
</td>
</tr>
</tbody>
</table>
Controller
angular.module("distCad").controller("adminCtlr", function($scope, $http, config, $window, $cacheFactory){
$scope.searchTerm = null;
$scope.hideSearcAlert = true;
$scope.companies = [];
$scope.cache = $cacheFactory('companyCache');
$scope.expireLogin = function(){
localStorage.removeItem("type");
$window.location.href = "/";
}
$scope.getResults = function(){
$scope.searchTerm = true;
$http.get("/api/companies").then(
function successCallback(response){
$scope.companies = response.data;
},
function errorCallback(response){
console.log("aaaa" + response);
}
);
}
$scope.getCompany = function(){
return $scope.cache.get("company");
}
$scope.setCompanyFromTable = function(index){
$scope.cache.put("company", $scope.companies[index]);
}
});
Destination View - Part where i am testing
<div class="container" ng-init="getCompany()">
<div class="row">
<div class="col-md-12">
<h2>Dados da empresa {{cache.get("company").companyName}}</h2>

How to remove extra added row for generated JSON on button click either using AngularJS or JavaScript?

I am performing few operations like Add and Remove for my two JSON files data.
My requirement is that I need to add respective json names and show them in the table and then need to generate json object for the added/selected json names on button click. It's working fine(that I can able to show my json names on UI table and can get/generate the json data object for my selected/added json names data after button click).
But, the issue is: after generating the json object or after clicking of Send button, I can see that one row is adding extra on my UI table after clicking of Send button, I don't need this added extra row for my UI table, I need only whatever I added the json names only those should be displayed in my table after clicking of Send button. It's happening for my two json tables.(I have two Send buttons individually, one for First JSON and other for Second JSON).
I am not sure what's the wrong here ? Please help me that to display the selected json names in table on button click, that shouldn't include one extra row adding either using AngularJS or JavaScript. Thank you in advance ! Created Plnkr.
html:
<div>
<p>First Table:</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in myFirstJson.Testing">
<td>{{getKey(value)}}</td>
<td><button ng-click="addFirst(value)">Add</button></td>
</tr>
</tbody>
</table>
<br> <br>
<table border="1" class="table">
<thead>
<tr>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in firstJsonNames track by $index">
<td>{{getKey(value)}}</td>
<td><button ng-click="deleteFirst($index)">Delete</button></td>
</tr>
<tr ng-hide="firstJsonNames.length > 0">
<td colspan="3">
<p>No Names</p>
</td>
</tr>
</tbody>
</table>
<br>
<br>
<table>
<tbody>
<tr>
<td>First Dropdown:<select ng-model="firstJsonNames.firstdropdown">
<option value="Test1">Test1</option>
<option value="Test2">Test2</option>
<option value="Test3">Test3</option>
</select><br />
</td>
</tr>
<tr>
<td>First Input:<input type="text" maxlength="50" size="50"
ng-model="firstJsonNames.firstInput" /> <br /></td>
</tr>
</tbody>
</table>
<br>
<br>
<button ng-click="generateFirstJson()">Send</button>
<br>
<br><p>Second Table:</p>
<table>
<thead>
<tr>
<th>Name</th>
<th>Add</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(key, value) in mySecondJson.MyTest">
<td>{{value.Main.static.name}}</td>
<td><button ng-click="addSecond(value.Main.static.name)">Add</button></td>
</tr>
</tbody>
</table>
<br>
<br>
<table border="1" class="table">
<thead>
<tr>
<th>Name</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="name in secondJsonNames">
<td>{{name}}</td>
<td><button ng-click="deleteSecond(name)">Delete</button></td>
</tr>
<tr ng-hide="mySecondJson.MyTest.length">
<td colspan="3">
<p>No Names</p>
</td>
</tr>
</tbody>
</table>
<br>
<br>
<label>Enter Second Input Data:</label> <input
ng-model="secondJsonNames.SecondInput" placeholder="Input Text"><br>
<br>
<button ng-click="generateSecondJson()">Send</button>
<br>
<br>
</div>
app.js:
var app = angular.module('myApp', ['ui.router']);
app.controller('TestCtrl',function($scope, $http,$state,$stateParams,filterFilter,$rootScope) {
$rootScope.firstJsonNames = [];
$scope.secondJsonNames = [];
$scope.firstJsonNames.firstdropdown="Test1";
$scope.firstJsonNames.firstInput="1.5";
if($rootScope.myFirstJson == undefined)
{
$http.get('test.json').success(function(response) {
$rootScope.myFirstJson = response;
});
}
$scope.addFirst = function (name){
$rootScope.firstJsonNames.push(name);
console.log($rootScope.firstJsonNames);
};
$scope.deleteFirst = function (index){
$rootScope.firstJsonNames.splice(index,1);
};
$scope.getKey = function(item) {
return Object.keys(item)[0];
};
$scope.generateFirstJson = function(){
$rootScope.firstJsonNames.push({firstdropdown:$rootScope.firstJsonNames.firstdropdown, firstInput:$rootScope.firstJsonNames.firstInput});
console.log(angular.toJson($rootScope.firstJsonNames));
};
//second json
if($rootScope.mySecondJson == undefined)
{
$http.get('test1.json').success(function(response) {
$rootScope.mySecondJson = response;
});
}
$scope.addSecond = function (name){
$scope.secondJsonNames.push(name);
console.log($scope.secondJsonNames);
};
$scope.deleteSecond = function (name){
index = $scope.secondJsonNames.indexOf(name);
$scope.secondJsonNames.splice(index,1);
};
$scope.generateSecondJson = function(){
$scope.secondJsonNames.push({SecondInput:$scope.secondJsonNames.SecondInput});
console.log(angular.toJson($scope.secondJsonNames));
};
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'main.html',
controller: 'TestCtrl',
});
});
You are updating $rootScope.firstJsonNames and $scope.secondJsonNames, which are used in ng-repeat, So values are displaying in table. Use new variable for json creation.
For you are reference:
I have used
$scope.newjson2 = [];
$scope.newjson1 = [];
Plunker
http://plnkr.co/edit/r0VTaaT2rcfkiBNqyRmt?p=preview
JS:
var app = angular.module('myApp', ['ui.router']);
app.controller('TestCtrl',function($scope, $http,$state,$stateParams,filterFilter,$rootScope) {
$rootScope.firstJsonNames = [];
$scope.secondJsonNames = [];
$scope.firstJsonNames.firstdropdown="Test1";
$scope.firstJsonNames.firstInput="1.5";
$scope.newjson2 = [];
$scope.newjson1 = [];
if($rootScope.myFirstJson == undefined)
{
$http.get('test.json').success(function(response) {
$rootScope.myFirstJson = response;
});
}
$scope.addFirst = function (name){
$rootScope.firstJsonNames.push(name);
console.log($rootScope.firstJsonNames);
};
$scope.deleteFirst = function (index){
$rootScope.firstJsonNames.splice(index,1);
};
$scope.getKey = function(item) {
return Object.keys(item)[0];
};
$scope.generateFirstJson = function(){
$scope.newjson1 = angular.copy($rootScope.firstJsonNames);
$scope.newjson1.push({firstdropdown:$scope.firstJsonNames.firstdropdown, firstInput:$scope.firstJsonNames.firstInput});
console.log(angular.toJson( $scope.newjson1));
};
//second json
if($rootScope.mySecondJson == undefined)
{
$http.get('test1.json').success(function(response) {
$rootScope.mySecondJson = response;
});
}
$scope.addSecond = function (name){
$scope.secondJsonNames.push(name);
console.log($scope.secondJsonNames);
};
$scope.deleteSecond = function (name){
index = $scope.secondJsonNames.indexOf(name);
$scope.secondJsonNames.splice(index,1);
};
$scope.generateSecondJson = function(){
$scope.newjson2 = angular.copy($scope.secondJsonNames);
$scope.newjson2.push({SecondInput:$scope.secondJsonNames.SecondInput});
console.log(angular.toJson($scope.newjson2));
};
});
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/home');
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'main.html',
controller: 'TestCtrl',
});
});

Define and get values from angularJS table

Here is my angularjs code to get values in a table and save. If I put some data in table and save, Its working fine but if I click save without entering any data in table it shows error as
TypeError: $scope.item is undefined
Here is my code and please help me. I am a newbie in angularJS
<div ng-app="Myapp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-route.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-messages.js"></script>
<script>
var Myapp = angular.module('Myapp', ["ngRoute"]);
</script>
<div ng-controller="orderFormController">
<table id="item_table">
<thead>
<tr class="headings">
<th class="column-title">Item </th>
<th class="column-title">Rate</th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" name="item" ng-model='item[0]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[0]'>
</td>
</tr>
<tr>
<td>
<input type="text" name="item" ng-model='item[1]'>
</td>
<td>
<input type="text" name="rate" ng-model='rate[1]'>
</td>
</tr>
</tbody>
</table>
<button type="button" ng-click='saveorder()' >SAVE ORDER</button>
</div>
<script>
Myapp.controller('orderFormController', ['$scope', '$http', function ($scope, $http) {
var data = {};
data['item'] = [];
$scope.saveorder = function () {
var rowCount = 3;
for (i = 1; i < rowCount; i++) {
data['item'][i] = {'item': $scope.item[i], 'rate': $scope.rate[i]}
}
alert(data);
}
}]);
</script>
$scope.item is not defined anywhere except for in that for loop, if there are no values in the table, then $scope.item will remain undefined. You could simply declare it prior to the for loop, and set some init values, which could be done in the controller, or by using the ng-init directive.
Also, I would recommend using the ng-repeat directive for your table rows, it will create a template per item from a collection, which makes your code easier to manage. Here's the documentation: ngRepeat
modify your html to only include this not 2 rows of input
<td>
<input type="text" name="item" ng-model='item'>
</td>
<td>
<input type="text" name="rate" ng-model='rate'>
</td>
and modify your saveOrder
$scope.saveorder = function () {
if (!($scope.item.length && $scope.rate.length)){
alert('can\'t be empty');
return;
}
data['item'].push({'item': $scope.item, 'rate': $scope.rate});
$scope.item = "";
$scope.rate = "";
console.log(data['item'][data['item'].length - 1]);
alert(data);
}

AngularJS: table edit data + update server

I have managed to create a table using AngularJS. In this table I show products from my datbase which can be filtered on category or some other keywords. Now the user should be able to alter this data in this table to update the data in the database.
AngularJS
categorieFilter = angular.module("categorieFilter", [])
categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){
$scope.search = "";
$scope.products = [];
$scope.categories = [];
store.getCategories().then(function(data){
$scope.categories = data;
})
store.getProducts().then(function(data){
$scope.products = data;
})
$scope.filterProductsByCats = function(category){
$scope.search = category;
};
}])
categorieFilter.factory('store', function($http, $q){
function _getCategory (){
var deferred = $q.defer();
$http.get('api/categories').success(function (data) {
deferred.resolve(data);
})
return deferred.promise;
}
function _getProducts (){
var deferred = $q.defer();
var prods = [];
$http.get('api/products').success(function (data) {
for(var i = 0;i<data.length;i++)
{
prods[i] = {name: data[i][0], category: data[i][2], price: data[i][1]};
}
deferred.resolve(prods);
})
return deferred.promise;
}
return {
getCategories: _getCategory,
getProducts : _getProducts
};
});
HTML table
<div ng-app="categorieFilter" ng-cloak="" ng-controller="catFilter">
<div class="input-group">
<input type="text" name="table_search" class="form-control input-sm pull-right" ng-model="search" placeholder="Search"/>
<div class="input-group-btn">
<button class="btn btn-sm btn-default">
<i class="fa fa-search"></i>
</button>
</div>
</div>
<div>
<input type="submit" class="btn btn-success" style="margin:10px; width:30%;" ng-repeat="cat in categories" ng-click="filterProductsByCats(cat.categoryName)" value="{{cat.categoryName}}">
</div>
<table class="table table-hover">
<tr style="background-color:#ddd;">
<th colspan="4" style="text-align:left; font-size:16px;"> Category </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Product </th>
<th colspan="4" style="text-align:left; font-size:16px;"> Price </th>
</tr>
<tr ng-repeat="product in products | filter:search | orderBy: 'category'">
<td colspan="4">{{product.category}}</td>
<td colspan="4">{{product.name}}</td>
<td colspan="4">{{product.price}}</td>
</tr>
</table>
Any ideas or reccomendations to get this done?
A library I like to use to achieve the editing of data, is angular xeditable. http://vitalets.github.io/angular-xeditable/
Then save it by posting it back to the webapi

AngularJS: post data to server

I want to add data to my database using AngularJS. First I have to choose a category from a list of categories which I get from my server. After that a user can add a product to the database. I tried accomplishing this using:
AngularJS
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
$scope.product = function($scope, $http, $catID){
$http.post(serviceBase + 'productadd/3/1/Icetealemon/5').then(function(results){
});
}
});
});
HTML
<table id="app2" ng-app="categories" ng-cloak="" class="table table-hover">
<tr >
<th colspan="5">Add product</th>
</tr>
<tr ng-form name="addproductForm" novalidate ng-controller="category">
<td colspan="1">
<select class="form-control m-b-10">
<option ng-repeat= "c in categories">{{c.categoryName}}</option>
</select>
</td>
<td colspan="1">
<select class="form-control m-b-10">
<option>Antwerpen</option>
<option>Leuven</option>
</select>
</td>
<td colspan="1">
<input type="text" class="form-control" placeholder="Name" ng-model="catID"></input>
</td>
<td colspan="1">
<input type="text" class="form-control" placeholder="Price" width="10%"></input>
</td>
<td colspan="1">
<input type="submit" class="btn btn-success" ng-click="product()"></input>
</td>
</tr>
</table>
I am not even using the ng-models to use the data of my html. It's still hard coded because it doesn't even work then. I am getting en error:
TypeError: Cannot read property 'post' of undefined
What am i doing wrong with my $http.post?
categories = angular.module('categories', []);
categories.controller("category",function($scope, $http){
var serviceBase = 'api/';
$http.get(serviceBase + 'categories').then(function (results) {
$scope.categories = results.data;
for(var i = 0; i < $scope.categories.length; i++){
var categories = $scope.categories[i];
}
$scope.product = function($scope, $http, $catID){
// NOTE: This '$http' is $scope.product function parameter
// variable `$http` not angular '$http'
$http.post(serviceBase + 'productadd/3/1/Icetealemon/5').then(function(results){
});
}
});
});
Remove $http parameter from $scope.product function.
Also, look at https://docs.angularjs.org/tutorial/step_05 about angular dependency issue during minification and how to solve it.

Categories

Resources