how to loop the data from database my route in laravel is Route::get('api/contacts', [ContactController::class, 'index'])->name('contact.index'); and im trying to display all the list but im confuse with the js code someone expert here and please help me
class ContactController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$contacts = Contact::all();
// return view('contacts.index', compact('contacts'));
return response()->json(compact('contacts'));
}
<script>
import axios from "axios";
export default {
data() {
return {
form: {
first_name: "",
last_name: "",
email: "",
city: "",
country: "",
job_title: "",
},
errorMessage: "",
user: "",
};
},
methods: {
processCreate() {
this.errorMessage = "";
axios
.post("/api/contacts/index")
.then((response) => {})
.catch((error) => {
this.errorMessage = error.response.data.message;
console.log("error", error.response);
});
console.log(response);
},
},
mounted() {
// console.log(this.form)
},
};
</script>
<template>
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Job Title</td>
<td>City</td>
<td>Country</td>
<td colspan="3">Actions</td>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
Show
</td>
<td>
Edit
</td>
<td>
<form method="post" action="">
<button class="btn btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<div>
<router-link :to="{ name: 'contactsCreate' }">New Contact</router-link>
</div>
</div>
</div>
</template>
you should have a variable for your contacts in vuejs instance
like contacts : []
and when you return your data in controller with axios to vuejs, you have to set response to that variable:
.then(response => {
this.contacts = response.data;
}
)
and then wherever you want your data to be shown :
<tr v-for="item in this.contacts">
<td>#{{item .name}}</td>
<td>#{{item .subject}}</td>
</tr>
Step 1: Load data from rest api
methods: {
loadContactsFromAPI() {
var self = this;
return axios
.get("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
self.contacts = response.data;
})
.catch(function (error) {
return error;
});
},
}
Step 2: Display the contact list to html template
<table class="table table-striped">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
<td>Email</td>
<td>Job Title</td>
<td>City</td>
<td>Country</td>
<td colspan="3">Actions</td>
</tr>
</thead>
<tbody>
<tr :key="index" v-for="(contact, index) in contacts">
<td>{{ index + 1 }}</td>
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.company.name }}</td>
<td>{{ contact.address.street }}</td>
<td>{{ contact.address.city }}</td>
<td>
Show
</td>
<td>
<a
href="#"
class="btn btn-primary"
#click.prevent="editContact(contact, index)"
>Edit</a
>
</td>
<td>
<button
class="btn btn-danger"
type="button"
#click="deleteContact(index)"
>
Delete
</button>
</td>
</tr>
</tbody>
</table>
Step 3: Implemented Edit or add new contact in html template
<div class="row" v-else-if="!showListContact">
<div>
<label>Name</label>
<input type="text" v-model="contact.name" />
</div>
<div>
<label>Email</label>
<input type="text" v-model="contact.email" />
</div>
<div>
<label>Job Title</label>
<input type="text" v-model="contact.company.name" />
</div>
<div>
<label>City</label>
<input type="text" v-model="contact.address.city" />
</div>
<div>
<button type="button" #click="saveContact">Save</button>
</div>
</div>
Step 4: Add Edit, Delete and Create new contact methods inside script
editContact(contact, index) {
this.showListContact = false;
this.selectedIndex = index;
this.contact = contact;
},
addNewContact() {
this.showListContact = false;
this.selectedIndex = "";
this.contact = {
company: {},
address: {},
};
},
saveContact() {
if (this.selectedIndex) {
this.contacts[this.selectedIndex] = this.contact;
} else {
this.contacts.push(this.contact);
}
// You have to make a call to backend api to save in db
this.showListContact = true;
},
deleteContact(index) {
if (confirm("Are you sure wants to delete the contact")) {
this.contacts.splice(index, 1);
// You have to make a call to backend api to delete in db
}
},
DEMO
For more details about Vue, Vuex, Form validations, Router, CRUD Operations, Table sorting, filtering refer the below project link
Complete Vue project with most of the features
Related
here is the code
the view code:
<input type="text" class="form-control" ng-model="model.org" />
<input type="button" class="btn btn-primary" value="Load Repos" ng-click="getRepos(model.org)" ng-hide="model.repos" />
<div class="col-md-6">
<table class="table table-striped" ng-show="model.repos">
<tr>
<th>Name</th>
<th>Language</th>
<th></th>
</tr>
<tr ng-repeat="r in model.repos">
<td>
<h4>{{r.name}}</h4> {{r.description}}
</td>
<td>{{r.language}}</td>
<td><input type="button" class="btn btn-success" ng-click="loadDetail(r.name)" value="Detail"> </td>
</tr>
</table>
</div>
and this is the inside the controller:
$scope.model = {
number: 0,
result: 'Ready'
};
$scope.getRepos = getRepos;
function getRepos(org) {
$http.get('https://api.github.com/orgs/org/repos').then(function(response) {
$scope.model.repos = response.data;
}, function(response) {
alert(response.error);
$scope.model.repos = 'Error: ' + response.data.message;
})
}
when I click the button that has the ng-click="getRepos(javascript); I get undefined but if I copied this link https://api.github.com/orgs/javascript/repos to a browser it returns data!
what am I missing here?
I think you wanted to pass the parameter to getRepos in your GET url, like:
function getRepos(org) {
$http.get('https://api.github.com/orgs/' + org + '/repos').then(function(response) {
$scope.model.repos = response.data;
}, function(response) {
alert(response.error);
$scope.model.repos = 'Error: ' + response.data.message;
})
}
I'm trying to generate a pdf from an html div with html2canvas and pdfMake but always got a blank page or just part of the div! How can I get the entire div content?
Here is the js code :
$scope.PrintFiche = function () {
var prom = new Promise(function (resolve, reject) {
html2canvas(document.getElementById('DevisImpression'), {
onrendered: function (canvas) {
var data = canvas.toDataURL("image/png");
var docDefinition = {
content: [{
image: data
}]
};
resolve(docDefinition);
}
});
})
prom.then(function (docDef) {
pdfMake.createPdf(docDef).download($scope.FicheName + ".pdf");
})
}
And the html :
<div class="Partie" id="DevisImpression">
<div id="PartieInner">
<h2 id="TitreDevis">
<b>
Etablissement du devis
</b>
</h2>
<div id="ImgVoitureDevis">
<img id="ImgVoitureAdapt" src="../../Assets/Images/test.jpg" />
</div>
<div id="OptMult">
<table id="TableDevis">
<tr>
<td class="td1">
Modèle :
</td>
<td class="td2">
{{modele.displayName}}
</td>
</tr>
<tr>
<td class="td1">
Classe :
</td>
<td class="td2">
{{classe.displayName}}
</td>
</tr>
<tr>
<td class="td1">
Moteur :
</td>
<td class="td2">
{{moteur.displayName}}
</td>
</tr>
<tr>
<td class="td1">
Couleur :
</td>
<td class="td2">
{{couleur.displayName}}
</td>
</tr>
<tr>
<td class="td1">
Jantes :
</td>
<td class="td2">
{{jante.displayName}}
</td>
</tr>
</table>
</div>
<table id="Devis">
<tr>
<th class="tdDevis2">
Options
</th>
<th class="tdDevis2">
Prix
</th>
</tr>
<tr ng-repeat="optionDev in optionsDevis">
<td class="td3">
{{optionDev.displayName}}
</td>
<td class="td4">
{{optionDev.prix}} €
</td>
</tr>
</table>
</div>
<h2 id="TotalTitre">
<b>
TOTAL
</b>
</h2>
<input type="text" id="Total" value="{{total}} €" disabled />
<br />
</div>
I have a simple solution. Try this.
$scope.downloadQuotation = function () {
html2canvas(document.getElementById('rosterPrintView'), {
onrendered: function (canvas) {
var data = canvas.toDataURL();
var docDefinition = {
content: [{
image: data,
width: 500
}]
};
pdfMake.createPdf(docDefinition).download("Roster.pdf");
}
});
};
Adding items from one array to a new array using:
$scope.listItems = [];
$scope.addToList = function(item) {
$scope.listItems.push(item);
console.log($scope.listItems);
};
<tr ng-repeat="x in data">
<td><{{ x.id }}</td>
<td><button type="button" ng-click="addToList(x.id)">Add to</button></td>
</tr>
Then printing the new array:
<tr ng-repeat="item in listItems">
<td>{{item.id}}</td>
</tr>
Would it be possible to change the attribute names of the new listItems array using user input?
Sure its possible. But not the way your code is written. You need to pass the object to the function, not the id.
<tr ng-repeat="x in data">
<td>{{ x.id }}</td>
<td><input type="text" ng-model="newVal"/></td> <!--this property can be changed by user-->
<td><button type="button" ng-click="addToList(x, newVal)">Add to</button></td>
</tr>
and in the controller function:
$scope.addToList = function(item, newVal) {
var newItem = item;
newItem.id = newVal;
$scope.listItems.push(item);
console.log($scope.listItems);
};
You could definitely do that, But for that you need to pass in the object in itself not x.id.
Here is a sample working solution.
var app = angular.module("sampleApp", []);
app.controller("sampleController", ["$scope",
function($scope) {
$scope.data = [{
id: "City-1"
}, {
id: "City-2"
}, {
id: "City-3"
}, {
id: "City-4"
}, {
id: "City-5"
}];
$scope.listItems = [];
$scope.addToList = function(item) {
$scope.listItems.push(item);
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="sampleApp">
<div ng-controller="sampleController">
<table>
<tr ng-repeat="x in data">
<td>
{{ x.id }}</td>
<td>
<button type="button" ng-click="addToList(x)">Add to</button>
</td>
</tr>
</table>
New List:
<table>
<tr ng-repeat="item in listItems track by $index">
<td>
{{ item.id }}</td>
<td>
<button type="button" ng-click="addToList(x)">Add to</button>
</td>
</tr>
</table>
</div>
</div>
I have the following angular table with an edit button
<table class="tableData" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th></th>
<th>Budget Name</th>
<th>Year</th>
<th>Month</th>
<th></th>
</tr>
</thead>
<tbody ng-repeat="(ind,O) in budgetdetails">
<tr ng-class-even="'even'" ng-class-odd="'odd'">
<td class="CX"><span>+</span></td>
<td>{{O.budget.BudgetName}}</td>
<td>{{O.budget.Year}}</td>
<td>{{O.budget.Month}}</td>
<td><input type="button" value="Remove" class="btn btn-primary" data-ng-click='removeRow(O)' />
<input type="button" value="Edit" class="btn btn-primary" data-ng-click='EditRow(O)' /></td>
</tr>
<tr class="sub">
<td></td>
<td colspan="5">
<table class="tableData" border="0" cellspacing="0" cellpadding="0">
<tr>
<th>Category</th>
<th>SubCategory</th>
<th>Amount</th>
</tr>
<tr ng-repeat="(indx,a) in O.budgetdetails" ng-class-even="'even'" ng-class-odd="'odd'">
<td>{{a.Category}}</td>
<td>{{a.Subcategory}}</td>
<td>{{a.Amount| currency}}</td>
</tr>
#* <tr>
<td colspan="2">Total</td>
<td></td>
<td>{{Totals().Amount| currency}}</td>
</tr>*#
</table>
</td>
</tr>
</tbody>
</table>
I want to be able to edit the data when I click on the edit button so far I have been playing with the angular controller and I have this
$scope.EditRow = function (item) {
$scope.budget = item.budget;
$scope.idBudget = item.budget.idBudget;
$scope.BudgetName = item.budget.BudgetName;
$scope.Year = item.budget.Year;
$scope.Month = item.budget.Month;
resp=BDetail.FindBudgetById(item.budget.idBudget);
};
The last line call a json and returns a set of data which I want to send to the page were I create the budgets for editing. Now I am not sure how to send the json to another page and the page that receives it is the View were I create the budgets and it has an IEnumerable editor to repeat the budgets details. Code is as follows
#model BudgetPortalMVC4.Models.budget
#{
ViewBag.Title = "NewBudget";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Scripts.Render("~/bundles/jquery")
<script src="../../Scripts/jquery.validate.js" type="text/javascript"> </script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<h2>NewBudget</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.BudgetName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BudgetName)
#Html.ValidationMessageFor(model => model.BudgetName)
</div>
</td>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Year)
</div>
<div>
#Html.DropDownListFor(model => model.Year, BudgetPortalMVC4.Controllers.BudgetController.GetDropDownListForYears())
#Html.ValidationMessageFor(model => model.Year)
</div>
</td>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Month)
</div>
<div>
#Html.DropDownListFor(model => model.Month, BudgetPortalMVC4.Controllers.BudgetController.GetDropDownListForMonth())
#Html.ValidationMessageFor(model => model.Month)
</div>
</td>
</tr>
</table>
</div>
<div>
<h3>Budget Detail</h3>
<div> <input type="button" id="addbudgetdetail" value="Add row" /></div>
<div id="new-budgetdetail">
#Html.EditorForMany(x => x.budgetdetails)
</div>
<input type="submit" />
</div>
#section Scripts{
<script type="text/jscript">
var url = '#Url.Action("GetSubCategories", "Budget")'; // Do not hard code your url's
$(document).on('change', '.SelectedCategory', function () {
var subCategory = $(this).closest('.item').find('.SelectedSubCategory');
subCategory.empty();
$.getJSON(url, { id: $(this).val() }, function (data) {
if (!data) {
return;
}
subCategory.append($('<option></option>').val('').text('Please select')); // Do not give the option a value!
$.each(data, function (index, item) {
subCategory.append($('<option></option>').val(item.Value).text(item.Text));
});
});
});
$(function () {
$('#addbudgetdetail').on('click', function () {
jQuery.get('#Url.Action("AddBudgetDetail", "Budget")').done(function (html) {
$('#new-budgetdetail').append(html);
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
});
});
$(".deleteRow").on("click", '', function () {
$(this).parents("#budgetRow:first").remove();
return false;
});
});
</script>
}
}
How can I accomplish passing the json data to this view and turning the view into and updating form instead of a create form?
I have this edit form on my index.html
<tbody>
<tr ng-repeat="client in vm.clients | orderBy: '-ClientID'" ng-dblclick="vm.clickEditAction(client)">
<td><img src="/img/trash.png" style="cursor: pointer;" ng-click="vm.removeAction(client)" alt="Remove {{ client.ClientID }}" /></td>
<td>{{ client.ClientID }}</td>
<td>
<span data-ng-hide="editMode">{{ client.ClientName }}</span>
<input type="text" data-ng-show="editMode" data-ng-model="client.ClientName" data-ng-required />
</td>
<td>{{ client.Country }}</td>
<td>{{ client.Email }}</td>
<td><button type="submit" data-ng-hide="editMode" data-ng-click="editMode = true; editAppKey(entry)" class="btn btn-default">Edit</button>
<button type="submit" data-ng-show="editMode" data-ng-click="editMode = false" class="btn btn-default">Save</button>
</td>
</tr>
</tbody>
However, every time I edit the field and submit it, it doesn't update the field in the table database.
Here's my controller save:
vm.saveAction = function () {
clientService.save(vm.clients, function (data) {
if (data.success) {
toastr.success('changes were saved.', 'Success');
vm.clients = data.records;
} else {
toastr.error('Error saving :\n\n' + data.errorMessage, 'Error', {
timeOut: 0
});
}
}, function (error) {
toastr.error('Error saving :\n\n' + error, 'Error', {
timeOut: 0
});
});
}