Checking deletion and update ui angular ngResource module - javascript

How can I check what is really happening in the below delete function? Every time I delete it says "Success" but the UI doesn't update .
HTML
<md-content >
<div id="main" class="well">
<table cellpadding="20" class="table table-bordered table-striped">
<tr>
<th ng-repeat="(head, value) in models[0]">
<span>{{head}}</span>
</th>
</tr>
<tr ng-repeat="row in models">
<td ng-repeat="(name, value) in row" ng-scope>
<span ng-click="" ng-bind="row[name]"></span>
</td>
<td >
<a target="_self" href="#" ng-click="downlaodId(row)">Downlaod</a>
</td>
<td >
<a target="_self" href="#" ng-click="deleteId(row)" confirmation-needed="Really Delete?">Delete</a>
</td>
</tr>
</table>
</div>
</md-content>
Controller
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id }, function(successResult) {
alert('Deleted');
}, function (errorResult) {
// do something on error
if (errorResult.status === 404) {
alert('Ooops');
}
});
};
my UI looks like this after click delete
fileLoadservice
app.factory('fileLoadService', ['$resource',
function ($resource) {
return $resource(
"http://jsonplaceholder.typicode.com/todos/:id",
{ id: "#id" },
{ query: { 'method': 'GET', isArray: true }
});
}]);

As you can see from your code:
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id },function(successResult) {
alert('Deleted');
}, function (errorResult) {
You are doing nothing to the current model, just sending an alert Deleted when you hit the delete button. If you want it to do something else..... you should put that functionality in the code.
For example:
$scope.deleteId = function (idPassed) {
fileLoadService.delete({ 'id': idPassed.id },function(successResult) {
var index = $scope.models.indexOf(idPassed);
$scope.models.splice(index, 1);
alert('Deleted');
}, function (errorResult) {

Related

Adding to List<Model> using JQuery

I have a ViewModel with a parameter List. In the View, the user should be able to add or remove from that list such that the added or removed users are reflected in the POST for that parameter. In JQuery, after clicking an "Add" button, an ajax call returns a UserModel variable, but a simple .append doesn't add to the list.
The other questions I've seen on this issue deal with Partial Views, but this situation updates the table of UserModel without needing a Partial View. It seems like there should be an easy way to do this. Does anyone know how to add the returned UserModel to the List in JQuery so that the List will be returned to the Post with the added models?
<script>
$("#bUser").on('click', function () {
var $addedRecipient = $("#AddedRecipient");
if ($addedRecipient.val() != null && $addedRecipient.val() != "") {
$.ajax({
type: "GET",
url: '#Url.Action("GetFullRecipient", "Message")',
data: { CompanyID: $("#CompanyID").val(), Employee: $addedRecipient.val() },
success: function (data) {
$("#Recipients").append(data);//Not adding to Recipients (Model.List<UserModel>) - is there a simple solution like this?
var bRow = $('<tr></tr>'),
bCell = $('<td style="display:none"></td>').append(data.UserID);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserFirstName);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserEmail);
bRow.append(bCell);
bCell = $('<td align="center"><input type="button" class="btn btn-info removeRecipient" value="Remove"></td>');
bRow.append(bCell);
$("#bTable tbody").append(bRow);//Works with returned data
$addedRecipient.val("");
},
error: function () {
alert("Recipient could not be added.");
}
});
}
});
</script>
this code worked perfect for me, you just have to go through this list, obviously you have to put the #model directive and a type list Recipient.
#model List<...Models.Recipient>
<input type="button" id="btnAdd" class="btn btn-primary" value="Add"
onclick="myfunction()"/>
<script>
function myfunction() {
$.ajax({
type: 'GET',
contentType:"application/json; charset=utf-8",
url: '#Url.Action("GetFullRecipient","Message")',
data: { CompanyID: $("#CompanyID").val(), Employee:
$addedRecipient.val()},
success: function (response) {
$("#containerData").html(response);
},
error: function (result) {
alert(result);
}
});
}
</script>
<div id="containerData">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Desc_Prod</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>#item.UserID</td>
<td>#item.UserFirstName</td>
<td>#item.UserEmail</td>
<td><a class="btn btn-danger" href="#Url.Action("DeleteRow","Message", new {item.UserID})">Delete</a></td>
</tr>
}
}
</tbody>
</table>
</div>
The answer here followed the link in freedomn-m's comment. Iterate through the Razor table using a for loop, then use a HiddenFor with the model parameter's ID and a CheckBoxFor as the model parameter's selecting field, and have a submit button with a unique name and value. When a button input is clicked and the value fits a given string, loop through the model and add a user that's not there or subtract a user that is there and return to the View.
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered" id="bTable">
<thead>
<tr>
<th style="display:none"></th>
<th style="display:none"></th>
<th class="text-center">Recipient</th>
<th class="text-center">E-mail</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
#if (Model.Recipients.Any())
{
for (var i = 0; i < Model.Recipients.Count; i++)
{
<tr>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientUserID)</td>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientCorporateID)</td>
<td align="center">#Model.Recipients[i].RecipientName</td>
<td align="center">#Model.Recipients[i].RecipientEmail</td>
<td align="center">#Html.CheckBoxFor(m => m.Recipients[i].RemoveRecipient)</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>

Dynamically add Select2 to Row

why when i try to add select2 to new row the new select2 failed to initialize (it shown as select html tag).
Here's my code to create the table :
<table id="tbldet" class="table table-bordered table-striped table-hover" style="width:100%;margin:0 auto;">
<thead>
<tr>
<th><p>Nama Barang</p></th>
<th><p>Harga</p></th>
<th><p>Qty</p></th>
<th><p>Total</p></th>
<th style="width:50px"><p>Aksi</p></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select class="select2" name="det_brg" style="width:100%;">
</select>
</td>
<td>10000</td>
<td>4</td>
<td>930000</td>
<td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>
</tr>
</tbody>
</table>
javascript function to initializeSelect :
function initializeSelect2(selectElementObj) {
selectElementObj.select2({
width: "80%",
tags: true,
language:"id",
ajax: {
url: "controller/barang_list.php",
dataType: "json",
type:"GET",
delay: 250,
data: function (params) {
return {
search: params.term
}
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
id:item.id,
text:item.text
}
})
};
},
cache: false
},
minimumInputLength: 3,
dropdownParent:$("#form-data")
});
};
$(".select2").each(function() {
initializeSelect2($(this));
});
here's the code to add new row :
//create new row
$("#add_row").click(function(e) {
//new row
$("#tbldet").append(
'<tr>\
<td>\
<select class="select2" name="det_brg" style="width:100%;">\
</select>\
</td>\
<td>10000</td>\
<td>4</td>\
<td>930000</td>\
<td><span class="btn btn-danger"><i class="fa fa-remove"></i></span></td>\
</tr>'
);
var newSelect=$(this).closest("tr").find(".select2");
initializeSelect2(newSelect);
})
i suspect there's problem with finding new 'select2' component on new row, but when i use alert(newSelect) it didn't show NULL / Undefined
Your suspicion is correct, your code will never find the new .select2 element. The reason has to do with the way .closest() works. You can investigate that here:
https://api.jquery.com/closest/
But in the mean time:
Change
var newSelect=$(this).closest("tr").find(".select2");
TO
var newSelect=$("#tbldet").find(".select2").last();

How to refresh ng-repeat table in AngularJS onclick button?

I can not update the value of the fields in the table with ng-repeat in any way onclick of a JS function, not even with a $ scope.apply () or with a timeout.
This is my HTML Code :
<div class="container">
<table class="table" id="table">
<thead class="table-bordered">
<th ng-repeat="(column_name,v) in response[0];">{{column_name}}<br>
<b>Class:</b>
<a ng-click="chooseClass(column_name)" id="{{column_name + 1}}">
{{kls_dict[column_name][0]}}
</a>
<br>
<b>Transfs:</b>
<a ng-click="chooseTrf(column_name)" id="{{column_name + 2}}">
{{kls_transfs[kls_dict[column_name][0]][0]}}
</a>
</th>
</thead>
<tbody>
<tr ng-repeat="row in response">
<td ng-repeat="value in row">{{value}}</td>
</tr>
</tbody>
</table>
</div>
And this is my JS function called in another HTML button component :
$scope.save_params = function (old_transformation, object) {
console.log("Enter save_params");
console.log("trfs", old_transformation)
console.log(object)
console.log('class', $rootScope.old_class)
console.log('columns_name', $rootScope.show_column_name)
to_send = {
'class': $rootScope.old_class,
'column_name': $rootScope.show_column_name,
"trfs": old_transformation,
"params": object
}
$rootScope.spm.close();
$http({
url: "/send_parameters",
method: "POST",
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(to_send)
}).success(function (data) {
console.log(data)
}).error(function () {
console.error('Errore durante invio dei parametri');
$("#warning-alert").text("Errore durante l'invio dei parametri, riprovare o controllare i parametri specificati");
$("#warning-alert").fadeTo(2000, 500).slideUp(500, function () {
$("#warning-alert").slideUp(500);
});
});
};
I have already specify the AngularJS controller. Thanks everyone :)

AngularJS get id of element clicked and use in controller

I just began learning AngularJS, and I am trying to create a pretty simple web application. Right now, I have some users. Each user is displayed in an individual table and each user has its own details which is displayed in a table under it.
$scope.userList = [{username: "Bob_t", detailsId: 1}, {username: "Mike_V", detailsId: 2}];
$scope.userDetails = [{Name: "Bob", Age: 20, id: "1"}, {Name: "Michael", Age: 18, id: "2"}];
You can see that each user has a reference to it's corresponding details (detailsId in userList corresponds to id in userDetails).
Basically, what I'm trying to do is initially have the details table hidden for each user. And when someone clicks the expand button for a specific user, open that user's corresponding details table and populate it with that user's details. What I'm having trouble with is getting the detailsId from the clicked expand button and then using that to query my DB to get the correct user's details to display in the table under it.
<div ng-repeat="user in userList | filter:searchBox">
<div class="uk-panel-box-secondary uk-overflow-container tableDiv uk-margin-large-bottom">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Username</th>
</tr>
</thead>
</table>
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="isOpened=!isOpened; showOrHideDetails(isOpened, param)" ng-class="{'uk-icon-plus-square-o': !isOpened, 'uk-icon-minus-square-o': isOpened}"></a>
</div>
<div class="uk-panel-box-secondary uk-overflow-container uk-margin-top uk-margin-large-left uk-margin-bottom tableDiv">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tr ng-repeat="details in userDetails" id={{user.id}}>
<td>{{details.Name}}</td>
<td>{{details.Age}}</td>
<td>
</td>
</tr>
</table>
</div>
</div>
my controller:
$http({
method : "GET",
url : "http://database:8081/userAccounts/"
}).then(function mySucces(response) {
$scope.userList = response.data;
}, function myError(response) {
// $scope.userList = response.statusText;
});
$scope.showOrHideDetails = function(isOpened, param)
if(isOpened){
console.log($scope.id)
$scope[id] = true;
console.log($scope.id);
$http({
method : "GET",
url : "http://database:8081/details?id=" + index
}).then(function mySucces(response) {
$scope.userDetails = response.data;
}, function myError(response) {
$scope.userDetails = response.statusText;
});
}
else{
$scope.showDetails = false;
}
}
What is really confusing to me is once I get the correct userDetails object after querying the DB, how do I populate the corresponding table with that info?
I know I probably need a model, but this confuses me because the number of users is unknown.
First, your code is a bit confuse..
After each query you're attributing the response (which one is the details of a single user) to the whole array userDetails:
$scope.userDetails = response.data;
While it should be:
$scope.userDetails.push(response.data);
In addition, you have a single variable called isOpened, for sure it won't work, because you have multiple buttons for only 1 variable.
So my suggestion is to change it to:
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="showOrHideDetails(user)" ng-class="{'uk-icon-plus-square-o': !user.isOpened, 'uk-icon-minus-square-o': user.isOpened}"></a>
Also you have to check if the userDetail is already in your userDetails array.
Finally, since you want to show the details based on the user, you can use the native filter, because you already have the id property of users in both arrays, as below:
<tr ng-if="user.isOpened" ng-repeat="details in userDetails | filter: { id: user.detailsId }" id={{user.id}}>
A simple demo:
(function() {
angular
.module('app', [])
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', '$http'];
function MainCtrl($scope, $http) {
$scope.userList = [{
username: "Bob_t",
detailsId: 1
}, {
username: "Mike_V",
detailsId: 2
}];
$scope.userDetails = [{
Name: "Bob",
Age: 20,
id: "1"
}, {
Name: "Michael",
Age: 18,
id: "2"
}];
$scope.showOrHideDetails = function(user) {
user.isOpened = !user.isOpened;
function mySuccess(response) {
$scope.userDetails.push(response.data);
}
function myError(response) {
console.log(response.statusText);
}
if (user.isOpened) {
$http.get('http://database:8081/details?id=' + user.id)
.then(mySuccess)
.catch(myError);
} else {
$scope.showDetails = false;
}
}
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.4/js/uikit.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/uikit/2.26.4/css/uikit.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="user in userList | filter:searchBox">
<div class="uk-panel-box-secondary uk-overflow-container tableDiv uk-margin-large-bottom">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr>
<td ng-bind="user.username"></td>
</tr>
</tbody>
</table>
<a class="uk-margin-bottom uk-margin-left" id="expandIcon" ng-click="showOrHideDetails(user)" ng-class="{'uk-icon-plus-square-o': !user.isOpened, 'uk-icon-minus-square-o': user.isOpened}"></a>
</div>
<div class="uk-panel-box-secondary uk-overflow-container uk-margin-top uk-margin-large-left uk-margin-bottom tableDiv">
<table class="uk-table uk-table-hover uk-margin-top">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tr ng-if="user.isOpened" ng-repeat="details in userDetails | filter: { id: user.detailsId }" id={{user.id}}>
<td ng-bind="details.Name"></td>
<td ng-bind="details.Age"></td>
<td>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
I hope it helps!!
have you tried passing user from
<div ng-repeat="user in userList | filter:searchBox">
to function showOrHideDetails(user)

how to pass an object in a directive to avoid duplicated result

hey everyone sorry to bother you all , i have trouble understanding some directive i want to display 2 element in one tooltip when i write it like this :
<div ng-repeat="xx in dev.validationdvd"> Validé </div>
this this my full code below :
<table class="table table-bordered" >
<thead><tr class="infoti" >
<th>Id Dev</th>
<th>Nom Dev </th>
<th>Nom Ecu</th>
<th>Etat</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr dir-paginate=" dev in devs | itemsPerPage:7 track by $index ">
<td >{{dev.id}}</td>
<td>{{dev.nomdev}}</td>
<td >{{dev.ecu.nomEcu}}</td>
<td ng-if="dev.validationdvd[0].etatvalid == 'Validé' ">** <div ng-repeat="xx in dev.validationdvd"> Validé </div>**</td>
<td ng-if="dev.validationdvd[0].etatvalid != 'Validé' ">Non Validé</td>
<td><button class="btn btn-gray" ng-click="displaydata(dev.id)" data-toggle="modal" data-target="#myModal" >Validé</button></td>
</tr>
</tbody>
</table>
here's what i got when you pass the mass each Validé has a value
but i want the tow of them in just one tooltip not every one will display value
here's my data format
{
id: 16633,
nomdev: "AUTORADIO RADIO_VD45",
ecu: {
nomEcu: "RADIO_VD45"
},
validationdvd: [
{
etatvalid: "Validé",
vehid: {
model: "A6 I"
}
},
{
etatvalid: "Validé",
vehid: {
model: "A3 I"
}
}
]
}
and finaly this the directive of the tooltip that i've been struggling to change it and to pass my data through but i couldn't understand how it works because using ng-repeat will always duplicate the data:
app.directive('tooltip', function () {
return {
restrict:'A',
link: function(scope, element, attrs)
{
$(element)
.attr('title',scope.$eval(attrs.tooltip))
.tooltip({placement: "right"});
}
}
})
does anyone have an idea how can i pass my selected data so i can display all the data in the tooltip , thank you

Categories