Displaying multiple jsons in VUE - function

So this is my code
<script>
export default {
name: "app",
data() {
return {
items: []
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items = res
return res
}),
this.makeAjaxCall("authors.json", "get").then(resA => {
this.items = resA
return resA
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>
</template>
I have the function makeAjaxCall that brings me the books.json, but I want to use it for multiple jsons.
I tried to call it under created, with a different json, authors.json, but it doesn't work.
I guess the syntax is wrong.
I know the function could have been created better, but I would like to keep its initial form or maybe add a parameter to be the json file.(Tried that, but didn't work for me)
Any ideas, pretty please?

To bind the data you have to declare first items: {books:[],authors:[]}
Also you are overwriting this.items use this.items.books and this.items.authors to assign.
Below is the example which works without ajax
new Vue ({
el: "#app",
data() {
return {
items: {books:[],authors:[]}
};
},
created: function() {
this.items.books = this.makeAjaxCall("books", "get");
this.items.authors = this.makeAjaxCall("authors", "get");
},
methods: {
makeAjaxCall:function(url, methodType){
if(url == 'books'){
promiseObj= [{name:'name11',author:'author11',genre:'genre11'},{name:'name12',author:'author12',genre:'genre12'}]
}else{
promiseObj= [{name:'name22',author:'author22',genre:'genre22'}]
}
return promiseObj;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.js"></script>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
<table class="authorsTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.authors" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img :src="item.imageUrl"></td>
</tr>
</tbody>
</table>
</div>

So I found the answer, after millions of tries and it's pretty simple.
<script>
import './styling.scss'
export default {
name: "app",
data() {
return {
items: {books:[], authors:[]}
};
},
created: function() {
this.makeAjaxCall("books.json", "get").then(res => {
this.items.books = res.books;
return res;
}),
this.makeAjaxCall("authors.json", "get").then(res => {
this.items.authors = res.authors;
return res;
})
},
methods: {
makeAjaxCall:function(url, methodType){
var promiseObj = new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open(methodType, url, true);
xhr.send();
xhr.onreadystatechange = function(){
if (xhr.readyState === 4){
if (xhr.status === 200){
//alert("xhr done ok");
var response = xhr.responseText;
var respJson = JSON.parse(response);
resolve(respJson);
} else {
reject(xhr.status);
//alert("xhr failed");
}
} else {
//alert("xhr processing");
}
}
//alert("request sent succesfully");
});
return promiseObj;
}
}
};
</script>
<template>
<div id="app">
<table class="booksTable">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Genre</th>
<th>Image</th>
<th>Availability</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items.books" :key="item.name">
<td>{{item.name}}</td>
<td>{{item.author}}</td>
<td>{{item.genre}}</td>
<td><img id="imageBook" :src="item.imageUrl"></td>
<td>
<button class="btn add"> Add</button>
<button class="btn edit"> Edit</button>
<button class="btn delete"> Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>

Related

Importing a JSON on angularJS with $http.get

Im learnign angularJs, and i want to import an array from a json on my controller Like that:
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
and im using a table to display the data on todos:
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
and this results on the flowing html page:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>Example</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<link href="../css/bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("demo", []);
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
</script>
</head>
<body ng-controller="demoCtrl">
<div class="panel">
<h1>To Do</h1>
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
</div>
</body>
The normal way of getting access to the json is from the data within the returned object from the http request - you are tying to use the entire returned object.
I use "response" as the return from the get request - then the data is "response.data". This is needed because there are other properties returned within the response object from the get request.
Try changing your promise to be as follows:
promise.then(function (response) {
$scope.todos = response.data;
});
Also you should be having a thead and th's and tbody in the table to show a more semantically correct table
<table class="table">
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</tbody>
</table>
Promise return entire response in callback Data is in response.data
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
// Entire response in callback
promise.then(function (response) {
$scope.todos = response.data; // Data is in response.data
});
});
More: https://docs.angularjs.org/api/ng/service/$http

dynamic V-for shows no result (Vue.js)

I'm trying to fill an array with a list of objects that comes from an api, the objects are coming normally, but when trying to move to the array and play in the v-for nothing appears.
Here's my data vars:
data() {
return {
elementsReport: [],
};
},
Here's my "computed" section:
computed: {
changeElements: {
get() {
return this.elementsReport;
},
set() {
return this.elementsReport;
}
}
}
Here's my api call:
this.elementsReport = this.getHistoryDeliveryPositionsByDriverIdAndDateAPI();
Here's my api function:
getHistoryDeliveryPositionsByDriverIdAndDateAPI() {
axios
.post("/web-api/reports/history-delivery-position/generate", {
driver_id: this.driver,
initial_date: this.initialDate,
final_date: this.finalDate
})
.then(({ data }) => {
_this.elementsReport = data;
})
.catch(function() {
alert("Erro ao filtrar relatórios");
});
}
Here's my html table with the v-for:
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
</tr>
</thead>
<tbody>
<tr v-for="elements in changeElements">
<td scope="row">{{elements.id}}</td>
<td></td>
</tr>
</tbody>
</table>
Have you tried to bind the key prop to the tr element?
Like this:
<tr v-for="elements in elementsReport" :key="elements.id">
<td scope="row">{{elements.id}}</td>
<td></td>
</tr>
Lots of things wrong with your code. I would recommend using tutorials to learn JavaScript and Vue.
1) There is no need for a computed here. Use elementsReport in the template.
<tr v-for="elements in elementsReport" :key="elements.id">
<td scope="row">{{elements.id}}</td>
<td></td>
</tr>
2) Your API function is wrong, and you are trying to set elementsReport twice. It should be:
getHistoryDeliveryPositionsByDriverIdAndDateAPI() {
return axios
.post("/web-api/reports/history-delivery-position/generate", {
driver_id: this.driver,
initial_date: this.initialDate,
final_date: this.finalDate
})
.then(({ data }) => {
return data;
})
.catch(function() {
alert("Erro ao filtrar relatórios");
});
}
3) Call it like:
this.getHistoryDeliveryPositionsByDriverIdAndDateAPI().then(data => {
this.elementsReport = data;
});

How to insert data to more AngularJS controllers with single ajax call in javascript

I am trying to make single ajax call to server and than to use response to call more AngularJS with same data. I use angular.min.js and ng-table.min.js to create html tables.
But it does not work for me.
Thank you for any help.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.8.3/ng-table.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ng-table/0.8.3/ng-table.min.css" />
<b>List of Orders 1:</b><br>
<div>
<div ng-controller="selectFilterController1">
<table ng-table="tableParams" id="datatable" class="table" show-filter="true" style="font-size: 11px;position: relative; width: 100%">
<tbody>
<tr ng-repeat="row in $data" ng-class="{'color-status-green': row.status === row.status}">
<td style="width:40px;white-space:nowrap;" title="Address from" data-title="'Address from'" filter="{board_address: 'text'}" sortable="'board_address'">{{ row.board_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Address to" data-title="'Address to'" filter="{dest_address: 'text'}" sortable="'dest_address'">{{ row.dest_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Last name" data-title="'Last name'" filter="{last_name: 'text'}" sortable="'last_name'">{{ row.last_name }}</td>
<td style="width:40px;white-space:nowrap;" title="Time" data-title="'Time'" filter="{created_at: 'text'}" sortable="'created_at'">{{ row.created_at }}</td>
</tr>
</tbody>
</table>
</div>
<br><b>List of Orders 2:</b><br>
<div ng-controller="selectFilterController2">
<table ng-table="tableParams" id="datatable" class="table" show-filter="true" style="font-size: 11px;position: relative; width: 100%">
<tbody>
<tr ng-repeat="row in $data" ng-class="{'color-status-green': row.status === row.status}">
<td style="width:40px;white-space:nowrap;" title="Address from" data-title="'Address from'" filter="{board_address: 'text'}" sortable="'board_address'">{{ row.board_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Address to" data-title="'Address to'" filter="{dest_address: 'text'}" sortable="'dest_address'">{{ row.dest_address }}</td>
<td style="width:40px;white-space:nowrap;" title="Last name" data-title="'Last name'" filter="{last_name: 'text'}" sortable="'last_name'">{{ row.last_name }}</td>
<td style="width:40px;white-space:nowrap;" title="Time" data-title="'Time'" filter="{created_at: 'text'}" sortable="'created_at'">{{ row.created_at }}</td>
</tr>
</tbody>
</table>
</div>
When I call function ajaxCallOrders(), response is transfered to controllers, but
var app = angular.module('ngTableApp', ['ngTable']);
var datax;
app.controller('selectFilterController1', function($scope, $http, $filter, $q, NgTableParams) {
var datax;
$scope.arrayTemp = [];
module1 = function(response){
$scope.myData = angular.fromJson(response.data);
angular.forEach($scope.myData, function(element) {
$scope.arrayTemp.push(element);
});
datax=$scope.array = $scope.arrayTemp;
$scope.tableParams = new NgTableParams({page: 1, count: datax.length}, {data: datax, counts: [10, 15, 20, datax.length]});
}
})
app.controller('selectFilterController2', function($scope, $http, $filter, $q, NgTableParams) {
var datax;
$scope.arrayTemp = [];
module2 = function(response){
$scope.myData = angular.fromJson(response.data);
angular.forEach($scope.myData, function(element) {
$scope.arrayTemp.push(element);
});
datax=$scope.array = $scope.arrayTemp;
$scope.tableParams = new NgTableParams({page: 1, count: datax.length}, {data: datax, counts: [10, 15, 20, datax.length]});
}
})
ajaxCallOrders = (function(){
var orderListData = {"token": authToken, "limit": "50"};
$.ajax({
type: 'POST',
url: 'orders.php',
data: JSON.stringify(orderListData),
contentType: 'application/x-www-form-urlencoded',
dataType: 'text',
processData: false,
success: function( data, textStatus, jQxhr ){
var response = data;
module1(response);
module2(response);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
To contain methods and data that are injectable to multiple controllers, create an AngularJS service.
app.service("orders", function($http) {
var orderListData = {"token": authToken, "limit": "50"};
var config = { params: orderListData };
var ordersPromise = $http.get("orders.php",config);
this.getPromise = function() {
return ordersPromise;
});
};
Usage:
app.controller('selectFilterController2', function(orders, NgTableParams) {
orders.getPromise().then(function(response){
$scope.array = response.data;
var xLength = $scope.array.length;
$scope.tableParams = new NgTableParams(
{page: 1, count: xLength},
{data: datax, counts: [10, 15, 20, xLength]}
);
}
})
The service uses the $http service to execute an XHR GET request and store a promise. The orders service can be injected into multiple controllers or other custom services. The getPromise method returns a promise which contains the response from the GET request.
For more information, see
AngularJS Developer Guide - Creating Services

select all checkboxes with angular JS

I am trying to select all checkboxes with one single checkbox. But how to do that?
This is my HTML:
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<!-- userlist -->
<!--<div id="scrollArea" ng-controller="ScrollController">-->
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
I create an extra checkbox to selecet and unselect all checkboxes.
JS:
.controller('UsersCtrl', function($scope, $http){
$http.get('users.json').then(function(usersResponse) {
$scope.users = usersResponse.data;
});
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = true;
});
};
});
I tried this too, but none of them works for me :(
$scope.checkAll = function () {
angular.forEach($scope.users, function (user) {
user.select = $scope.selectAll;
});
};
You are missed the container divs with ng-controller and ng-app and angular.module.
user.select = $scope.selectAll is the correct variant.
https://jsfiddle.net/0vb4gapj/1/
Try setting the checked boxes against each user to be checked when the top checkbox is checked:
<input type="checkbox" ng-model="selectAll"/>
<table class="table">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Select</th>
</tr>
<tr ng-repeat="user in users | filter:search">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td><input type="checkbox" ng-click="usersetting(user)" ng-model="user.select" ng-checked="selectAll"></td>
<td><tt>{{user.select}}</tt><br/></td>
</tr>
</table>
Here is a JSFiddle you can use ng-checked with a variable on it like user.checked (or use the user.select as you want)
<div ng-app="app" ng-controller="dummy">
<table>
<tr ng-repeat="user in users">
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>
<input type="checkbox" ng-click="usersetting(user)" ng-checked="user.checked" ng-model="user.select">
</td>
<td><tt>{{user.select}}</tt>
<br/>
</td>
</tr>
</table>
<button ng-click="checkAll()">Check all</button>
</div>
JS:
var app = angular.module("app", []);
app.controller('dummy', function($scope) {
$scope.users = [{
id: 1,
name: "Hello",
select: 1
}, {
id: 2,
name: "World",
select: 1
}, ];
$scope.checkAll = function() {
angular.forEach($scope.users, function(user) {
user.checked = 1;
});
}
});
Simple use the following code
HTML
<input type="checkbox" ng-model="checkboxes.checked" data-ng-click="checkAll()" class="select-all" value="" />
JS
$scope.checkAll = function() {
angular.forEach($scope.users, function(item) {
$scope.checkboxes.items[item._id] = $scope.checkboxes.checked;
$scope.selection.push(item._id);
});
}

using ng-repeat to display data in json file

I am new to angularjs. I want to display the data in the following json file using ng-repeat.
http://www.cricbuzz.com/api/match/current
But I'm confused as there is a number in the data as key to each object. Can someone help me?
THis is a basic way to do it
Partial
<div ng-controller="Ctrl" >
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in rows">
<td>#{{ row.id}}</td>
<td>{{ row.series.name | uppercase }}</td>
</tr>
</tbody>
</table>
</div>
Controller
angular.module('app').controller('Ctrl', ['$scope', 'Resource', function ($scope, Resource) {
var pageChanged = function () {
$scope.myPromise = Resource.get({}, function (response) {
$scope.rows = response;
});
};
pageChanged();
}])
.factory('Resource', ['$resource', function($resource) {
return $resource('http://www.cricbuzz.com/api/match/current', {
}, {
'get': {
method: 'GET',
headers: {"Content-Type": "application/json"}
}
});
}]);