How to create $http delete req in angularjs - html

All i want is to delete a row of a table by clicking a button. I am diong something like this
.controller('removeInput' , function($scope, $http) {
$scope.remove = function(index){
var inputId = {'inputId': $scope.inputId};
$http.delete(baseUrl + '/input/' ,inputId, _auth)
.success(function (){
console.log('deleted');
}).error(function(err){
console.log(err);
});
};
});
and in html its something like this
<tbody ng-controller = "input">
<tr ng-repeat = "inputs in inputData">
<td ng-model = "inputId">{{inputs.inputId}}</td>
<td><img ng-src = "{{inputs.thumbnailUrl}}"/></td>
<td>{{inputs.filename}}</td>
<td></td>
<td>{{inputs.updatedAt.date}}</td>
<td ng-controller = "removeInput">
<a class = "btn btn-option" ng-click = "remove(index)">
<span class = "glyphicon glyphicon-remove"></span>
</a>
</td>
</tr>
</tbody>
and its not working. Please suggest where I am wrong?

You aren't really passing the correct value here. It's not clear what $scope.inputId is, but it isn't the value of the item you are trying to remove. Try this instead:
<a class = "btn btn-option" ng-click = "remove(inputs.inputId)">
and in the JavaScript:
$scope.remove = function(index){
$http.delete(baseUrl + '/input/' + index, _auth)
....

Related

Modifying table ejs with addEventListener won't stop

I have a table of dynamically generated data with nodejs and have to modify it like an excel in the browser. I have the element that interest me (the first one passed) but also the rest of the whole table which doesn't interest me. How can I make it stop? I've tried e.stopPropagation()
My generated table, I've only worked with "denomination for the moment
<% for (var i=0; i<nomenclature.length; i++){ %>
<tr>
<td>
<a class="bouton" href="/nomenclature/<%= nomenclature[i].idPiece %> ">Ajout bon de commande</a>
</td>
<td id="idPiece<%=i%>" name="idPiece">
<%=nomenclature[i].idPiece %>
</td>
<td contenteditable='true' id="denomination<%=i%>" class="denomination1">
<%=nomenclature[i].denomination %>
</td>
<td contenteditable='true' class="n_piece_plan">
<%=nomenclature[i].n_piece_plan %>
</td>
<td contenteditable='true'>
<%=nomenclature[i].rev %>
</td>
<td contenteditable='true'>
<%=nomenclature[i].qte %>
</td>
<td contenteditable='true'>
<%=nomenclature[i].unite %>
</td>
<td contenteditable='true'>
<%=nomenclature[i].matiere %>
</td>
</tr><script>
My script see below
</script>
<% } %>
</table>
My script in ejs
var all = document.getElementsByTagName("td");
for (var j=1; j<all.length;j++){
all[j].addEventListener("input", function(e) {
const newData = this.innerHTML;
const myID = document.getElementById("idPiece<%=i%>").innerHTML;
const myColumn = this.className;
const data = {newData, myID, myColumn};
const options = {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(data)
};
fetch('./nomenclature/inter/modification', options);
e.stopPropagation();
}, false);
}
My controller
exports.nomenclatureModification = function(request, response){
let newData = request.body.newData;
let myID = request.body.myID;
newData = newData.replace(/(\r\n|\n|\r|\s)/gm,"");
myID = myID.replace(/(\r\n|\n|\r|\s)/gm,"");
let myColumn = request.body.myColumn;
console.log(newData +" ahiiiiii "+ myColumn +" rooooh "+ myID);
/*
connection.query('UPDATE nomenclature SET ?? = ? WHERE idPiece = ?;',[myColumn,newData,myID], function(error, resultSQL){
if (error) throw error;
else{
console.log("modif enregistrer en bdd");
}
});
*/
response.redirect('/nomenclature');
}
The first element passed thru the console.log is the one I've modified and so my sql query can be made with that one (I can change easily every column). But because my script is nested inside the loop (to obtain idPiece[i] of my changed row) it also prints out the rest which I would like to stop.
EDIT: found a solution:
got the script out of the loop
changed my table with a id for each
<td contenteditable='true' id="<%=i%>" class="n_piece_plan">
<%=nomenclature[i].n_piece_plan %>
</td>
script change to access that id
for (var j=0; j<all.length;j++){
all[j].addEventListener("input", function(e) {
const newData = this.innerHTML;
let stringID = 'idPiece' + this.id;
const myID = document.getElementById(stringID).innerHTML;
const myColumn = this.className;
const data = {newData, myID, myColumn};
const options = {
method: 'POST',
headers: {
'Content-Type':'application/json'
},
body: JSON.stringify(data)
};
fetch('./nomenclature/inter/modification', options);
e.stopPropagation();
}, false);
}
I can now modify my table in the browser exactly like an Excel table and update that in my db. Performance is ok.

document.write a json vector to a table

Firstly I get orders:
app.controller('customersController', ['$scope', '$http', function($scope,$http) {
$http.get("http://18ff2f50.tunnel.mobi/yii2-basic/tests/Customers_JSON.json")
.success(function (response)
{
console.log("debug",response);
$scope.orders = response;
});
In an order I have a detail:
<div class="row" ng-repeat="x in orders|orderBy:'order_id'">
....
<div class="col right">
<button ng-click="viewOrderDetails(x.detail)">订单详情</button>
</div>
I have a json vector (which is returned from the server) stored in "detail" like this:
"detail":
"{\"4\":
{\"num\":2,
\"id\":\"4\",
\"name\":\"\\u86cb\\u7092\\u996d\",
\"price\":\"10.00\",\"total\":20},
\"6\":
{\"num\":1,
\"id\":\"6\",
\"name\":\"\\u626c\\u5dde\\u7092\\u996d\",
\"price\":\"10.00\",\"total\":\"10.00\"},
\"5\":
{\"num\":1,
\"id\":\"5\",
\"name\":\"\\u51b0\\u6dc7\\u51cc\",
\"price\":\"8.00\",\"total\":\"8.00\"
}}"
$scope.viewOrderDetails = function viewOrderDetails(detail) {
var newWin = open('orderdetails.html','windowName','height=300,width=300');
newWin.document.write('html to write...\n');
newWin.document.write(detail);
newWin.document.write('<input type="button" value="Close this window" onclick="window.close()">');
}
I want it displayed in a new window like this:
how should I do the document.write? Thanks.
You can use $compile service to compile template to write into new window:
app.controller('customersController', function($scope, $http, $compile) {
$http.get("order.json").success(function(response) {
$scope.x = response;
});
$scope.viewOrderDetails = function viewOrderDetails(order) {
var newWin = open('', 'windowName', 'height=300,width=300');
var template =
'<div>' +
'<table>' +
'<tr ng-repeat="(key, value) in order">' +
'<td>{{value.name}}</td>' +
'<td>{{value.id}}</td>' +
'<td>{{value.price}}</td>' +
'<td>{{value.total}}</td>' +
'</tr>' +
'</table>' +
'<input type="button" value="Close this window" onclick="window.close()">' +
'</div>';
$scope.order = order;
var table = $compile(template)($scope);
newWin.document.body.appendChild(table[0]);
}
});
Demo: http://plnkr.co/edit/pMCClUYMkpeyMiFwphrj?p=preview
Please take a look the code below, If you don't want to use jQuery, and want to use document.write() way. Use this code in your orderdetails.html file
<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>Price</th><th>Total</th>
</tr>
</thead>
<tbody>
<script>
var detail = window.opener.detail;
for(key in detail) {
document.write("<tr><td>"+ detail[key]["num"] +"</td><td>"+ detail[key]["name"] +"</td><td>"+ detail[key]["price"] +"</td><td>"+ detail[key]["total"] +"</td></tr>");
}
</script>
</tbody>
</table>
Please let me know if it is not working.

How can i make pagination through AngularJS?

Recently I create a AngularJs App . Thats code are below
HTML :
<div ng-app="" ng-controller="Hello">
<ul>
<li ng-repeat="x in greeting">
{{ x.user_name }}
</li>
</ul>
</div>
And my JS code is:
function Hello($scope, $http) {
$http.get('http://localhost/google/cibl/dashboard/get_all_user').
success(function(data) {
$scope.greeting = data;
});
}
Its working fine. This http service give me 2000 row now i want to paginate this by AngularJs. How can I do that ?
In your controller
app.controller('Hello', function($scope){
$scope.pageSize = 10;
$scope.currentPage = 0;
$scope.changePage = function(page){
$scope.currentPage = page;
}
})
In your mark up, you should have
<div ng-app="" ng-controller="Hello">
<ul>
<li ng-repeat="x in greeting | startFrom: currentPage * pageSize | limitTo: pageSize">
{{ x.user_name }}
</li>
</ul>
</div>
We're missing the startFrom filter so lets create that
app.filter('startFrom', function() {
return function(input, start) {
start = +start; //parse to int
return input.slice(start);
}
});
Now all thats left is the paginating panel, I'll leave it up to you to pretty it with css
<ul class="pagination" >
<li ng-repeat="page in pagination" ng-class="{'active':currentPage == page}"><a ng-click="changePage(page)">{{page + 1}}</a></li>
</ul>
Notes:
The reason why we use changePage() instead of currentPage = page is due to ng-repeat which could break some of the variables
In your anchor () tag, instead of ng-click, you can use a href to mark the page and in your controller, watch the page ref and change based on the queries. The benefits to this is that when you decide to do SEO for your website, it will be ready for that!
href="#!/partialname?page={{page}}"
You can do this way:
Pagination Example: http://jsfiddle.net/2ZzZB/56/
Found it in this question:
Pagination on a list using ng-repeat
At least I got a solution and its work properly :
HTML :
<div ng-controller="userController" class="jumbotron">
<h2>User List</h2>
<table class="table table-striped">
<thead>
<tr>
<th>User </th>
<th>Group</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr dir-paginate="u in users | itemsPerPage : 5">
<td>{{u.user_name}}</td>
<td>{{u.user_type}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls on-page-change="pageChanged(current)" template-url="<?php echo base_url(); ?>js/dirPagination.tpl.html"></dir-pagination-controls>
</div>
and JS :
Here i use AngularJs pagination directive
function userController($scope, $http) {
$scope.users = [];
$scope.total = 0;
$scope.perPage = 25; // this should match however many results your API puts on one page
getUsers(1);
$scope.pagination = {
current: 1
};
$scope.pageChanged = function (newPage) {
getUsers(newPage);
};
function getUsers(pageNumber) {
// this is just an example, in reality this stuff should be in a service
$http.get(app.baseUrl + 'dashboard/get_all_user/' + pageNumber)
.success(function (data) {
console.log(data);
$scope.users = data.users;
$scope.total = data.total;
})
.error(function (data) {
console.log(data);
alert("There was a problem. Please try again later.");
});
}
};
var myApp = angular.module('myApp', ['angularUtils.directives.dirPagination']);
var app = app || {};
app.baseUrl = '<?= base_url() ?>';
myApp.controller('userController', userController);

Angularjs does not update the data retrieved from the $http service

I'm trying to retrieve some data from a service using Angularjs. Initially, I want to just show the first 10 elements. Then, when the user clicks on a button (with ng-click="next()"), I want the same function to be triggered again in order to get the next 10 elements.
Here's my controller:
Admin.controller('orders', function ($scope, $http) {
var startIndex = 0;
const count = 10;
function retrieveData(startIndex, count) {
$http({
method: 'POST',
url: '/Admin/order/GetOrders',
data: { "startIndex": startIndex, "count": count }
})
.success(function (data) {
$scope.orders = data;
startIndex = startIndex + count;
$scope.$apply();
});
};
retrieveData(startIndex, count);
$scope.next = retrieveData(startIndex, count);
};
Now, what happens is that the function retrieveData() works perfectly the first time, but when I click the button nothing happens. I know for sure that the "click" event triggers the function, because I tried to replace the code with an alert, but I don't understand why the function retrieveData() itself only works the first time.
What am I missing?
<div class="container admin" ng-controller="orders">
<table class="table">
<tbody>
<tr ng-repeat="order in orders| filter:{OrderStatus: 'Hto'} | filter:query | filter:'!'+showCancelled | orderBy:predicate:reverse">
<td>
{{order.UserName}}
</td>
<td>
<span ng-class="{ 'label label-danger' : isLate }">
{{order.OrderDate}}
</span>
</td>
<td>
{{order.Country}}
</td>
<td>
<span ng-class="{ 'label label-warning' : order.OrderStatus == 'HtoPreAuth' || order.OrderStatus == 'SalePreAuth'}">
{{order.OrderStatus}}
</span>
</td>
</tr>
</tbody>
</table>
<a href="" ng-click="retrieveData()">
next
</a>
</div>
You are supposed to make the changes inside the $apply method:
Admin.controller('orders', function ($scope, $http) {
var startIndex = 0;
const count = 10;
$scope.retrieveData() { // No parameters
$http({
method: 'POST',
url: '/Admin/order/GetOrders',
data: { "startIndex": startIndex, "count": count }
})
.success(function (data) {
startIndex = startIndex + count;
$scope.orders = data;
if(!$scope.$$phase) {
$scope.$digest();
}
});
}
$scope.retrieveData();
};
// And the view
<a ng-click="retrieveData()"></a>
Edit:
Remove the parameters from the $scope.retrieveData function since they will be undefined
if you call the function with ng-click="retrieveData()"

Highlight rows of my table where checkbox is checked with knockout

I have an html table with a checkbox on first column. I would like to highlight the row where checkboxes are checked with knockout.
<table class="defaultGrid">
<thead>
<tr>
<th>Check</th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: model.Things">
<tr>
<td><input type="checkbox" data-bind="click: $root.selectThing " /></td>
<td data-bind="text: ID"></td>
<td data-bind="text: Name"></td>
</tr>
</tbody>
</table>
Here is an example on jsFiddle: http://jsfiddle.net/jJ4H6/1/
I don't know how to proceed. I don't want to add an extra property on my model like 'isSelected'.
Any idea?
Thanks.
I would definitely add a knockout observable to your 'Thing' that determines whether or not your tr element has a yellow background or not.
However, if you really don't want to add something like this to your view model, you'll have to add some logic to your selectThing function to handle this for you e.g.
self.selectThing = function(item, event) {
$(event.target).parent().parent().addClass('selected');
};
Check out this Jfiddle http://jsfiddle.net/jJ4H6/27/
$(function() {
Thing = function(id, name, selected) {
var self = this;
self.ID = id,
self.Name = name
self.isChecked = ko.observable(false);
};
function viewModel() {
var self = this;
self.model = {};
self.model.CurrentDisplayThing = ko.observable();
self.model.Things = ko.observableArray(
[
new Thing(1, "Thing 1"),
new Thing(2, "Thing 2"),
new Thing(3, "Thing 3")
]);
self.selectThing = function(item) {
};
}
ko.applyBindings(new viewModel());
});