VueJS Resource plugin example - javascript

I am attempting to display a JSON response from PHP. I was pointed in the direction of the VueJS resource plugin. Unfortunately, the examples it gives are vague at best.
Is anyone able to provide a simple example of how to display the return JSON object in a list?

HTML:
<table id="list-items">
<tr v-for="item in items">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</table>
JS:
new Vue({
el: '#list-items',
data: {
items: []
},
ready: function() {
this.items = this.getItems();
},
methods: {
getItems: function() {
this.$http.get('items.php', function(data){
this.items = data;
});
}
}
});
items.php must return a JSON encoded array like this:
[{id: 1, name: 'foo'},{id: 2, name: 'bar'}]

In vue 1.0.1 you can use v-for instead of v-repeat like this:
<table id="list-items">
<tr v-for="item in items">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
</tr>
</table>

I think you are looking for
{{ $data | json }}

Related

How to loop in AngularJs

I am new to Angular, maybe is a fool question.
I have a result from my AngularJs and I return an Array of values:
This is the code:
$scope.searchTitle = function () {
$http.post('/svn/cms2/branches/create_function/cms/includes/find.php', {
name_title: $scope.title
})
.success(function (result) {
console.log(result);
$scope.resultName = result;
$scope.ok = "we post";
})
.error(function (data, status) {
console.log(data);
});
};
And now i have the resultName in the html and i can see the result if i do this:
<p>{{ resultName[0].article_titile }}</p>
Question:
I want to display all the array. How can I display all?
P.S.:
I use this and it is not work
<tr ng-repeat="i in [3] | toRange" >
<td>{{ resultName[i].article_titile }}</td>
</tr>
But is not working
You need to use an iterator variable (e.g. result) with your resultName array in your ng-repeat:
<tr ng-repeat="result in resultName | toRange" >
<td>{{ result.article_titile }}</td>
</tr>

AngularJS Binding doesn't seem to work

I'm fairly new to Angular, and a simple binding doesn't work for me.
It just shows me {{ trip.name }} and {{trip.created}} just as they're written.
My controller:
(function () {
"use strict";
angular.module("app-trips")
.controller("tripsController", tripsController);
function tripsController() {
var vm = this;
vm.trips = [{
name: "US Trip",
created: new Date()
}, {
name: "World Trip",
created = new Date()
}];
A part of my class:
#section Scripts {
<script src="~/lib/angular/angular.min.js"></script>
<script src="~/js/app-trips.js"></script>
<script src="~/js/tripsController.js"></script>
}
<div class="row" ng-app="app-trips">
<div ng-controller="tripsController as vm" class="col-md-6 col-md-offset-3">
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in vm.trips">
<td>{{ trip.name }}</td>
<td>{{ trip.created }}</td>
</tr>
</table>
</div>
the view of the controller:
(function () {
"use strict";
angular.module("app-trips", ['ngSanitize']);
})();
BTW - supposedly according to the course I'm following, I don't need ['ngSanitize'] yet, but without it it doesn't even show the DIVs.
EDIT: as #jellyraptor noticed , I had a typo with = instead of :
EDIT 2 :
It was the typo + the [ngSanitize] which I really didn't needed. I fixed the typo and passed an empty array and everything works. Thanks all
Either Angular isn't loading or it is encountering an error. Bring up the dev tools with F12 and see if there are errors in the console. Also in the console, you can type 'angular' and hit enter and if it reports that angular is undefined then angular is not loading properly.
Because you are using controllerAs syntax and here the variable is vm. so for access scope object use vm instead of tripsController
<tr ng-repeat="trip in vm.trips">
<td>{{ trip.name }}</td>
<td>{{ trip.created }}</td>
</tr>
(function() {
"use strict";
angular.module("app-trips", []);
})();
angular.module("app-trips")
.controller("tripsController", tripsController);
function tripsController() {
var vm = this;
vm.trips = [{
name: "US Trip",
created: new Date()
}, {
name: "World Trip",
created: new Date()
}];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.2/angular.min.js"></script>
<div ng-app="app-trips" ng-controller="tripsController as vm" class="col-md-6 col-md-offset-3">
<table class="table table-responsive table-striped">
<tr ng-repeat="trip in vm.trips">
<td>{{ trip.name }}</td>
<td>{{ trip.created }}</td>
</tr>
</table>
</div>
You put an equals sign in your trips array's second object's 'created' attribute.
vm.trips = [{
name: "US Trip",
created: new Date()
}, {
name: "World Trip",
created = new Date()
}];
should be
vm.trips = [{
name: "US Trip",
created: new Date()
}, {
name: "World Trip",
created: new Date()
}];

Getting related array element AngularJS

I have a php api that returns a list of companies and a list of users,
Each user has a company_id assigned.
(Users : CustomerList) (Companies : CompanyList)
The companies have a company_id and company_name value.
I'm using resolve to get both these arrays.
When displaying the CustomerList, the company_id of the customer is displayed and everything is working fine.
But what i require is instead of the company_id being shown, I need the company_name being displayed in the CustomerList.
The company_id of the CustomerList is related to the id in the CompanyList.
Just that the company_name is contained in the companyList and not in the CustomerList. But the ID's are related and contained in the userList.
I need to get the company_name of the id that's in CustomerList and display it in the view.
resolve: { userList:function($http,$stateParams){
return $http.post('/api/get_users.php',{role:$stateParams.role},{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }})
.then(function(response){
console.log(response);
return response.data.data;
})
},
companyList:function($http,$stateParams){
return $http.get('/api/get_companies.php')
.then(function(response){
console.log(response);
return response.data.data;
})
}
}
controller("CustomerList", function($scope,$location,$http,$stateParams,userList,companyList){
$scope.customers = userList;
$scope.companies = companyList;
})
VIEW
<table>
<thead>
<tr>
<th>Username</th>
<th>Company Name</th>
<th>Contact Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.username }}</td>
<td>{{ customer.company_id }}</td>
<td>{{ customer.contact_name }}</td>
</tr>
</tbody>
</table>
the customer.company_id is related to the ID in the companyList , i need to return the companyList.company_name instead of showing the company ID in the customers.
Thanks in advance for any help.
You need to join them.
So you need to create a new object with will contain the username, contact_name, company_name and other properties you need. You need to use the map() which will return an array of new objects. With username and contract_name it is easy, just assign the properties to the new created object. With company_name, we need to find the appropriete company and assign it's name to the newly created object.
Working Example with simple data, which joins two arrays based on the id.
var app = angular.module('app', []);
app.controller('ctrl', ['$scope', function($scope){
var userList = [
{username: 'A user', contact_name: 'A contract', company_id: 1},
{username: 'B user', contact_name: 'B contract', company_id: 2},
{username: 'C user', contact_name: 'C contract', company_id: 3},
];
var companyList = [
{id: 1, name: 'A Company'},
{id: 2, name: 'B Company'},
{id: 3, name: 'C Company'},
];
$scope.customers = userList.map(item => {
var foundCompany = companyList.find(company => company.id === item.company_id);
return {
username: item.username,
contact_name: item.contact_name,
company_name: foundCompany ? foundCompany.name : ''
};
});
$scope.companies = companyList;
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
<table>
<thead>
<tr>
<th>Username</th>
<th>Company Name</th>
<th>Contact Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="customer in customers">
<td>{{ customer.username }}</td>
<td>{{ customer.company_name }}</td>
<td>{{ customer.contact_name }}</td>
</tr>
</tbody>
</table>
</body>
You can structure your companies list in such a way that each object in list is key value pair with key being id of company and value being complete object of company details and then access it easily.
eg
$scope.companies = {
{
"companyId1" : {
"name" : "companyName",
"field2" : "vlue2"
}
},
{
"companyId2" : {
"name" : "companyName2",
"field2" : "vlue2"
}
}
}
and then in your html access it using
{{companies[customer.company_id].name}}
This will work for you
map your userList so that it will contain companyName
var mappedCustomerList= userList.map(function(user){
var user=userWithCompanyName;
userWithCompanyName['companyName']=
companyList[companyList.findIndex(function(company){return company['id']==user['company_id']})].companyName;
return userWithCompanyName;
});
$scope.customerList=mappedCustomerList;
so then from your view you can access companyName
<td>{{customer.companyName}}</td>

Display data in Vue.js with v-for

I'm making a simple shopping cart system using Laravel and Vue.js. I can successfully add items to my shopping basket and retrieve them to a certain point, but I'm having trouble actually outputting the items to the view.
When I hit my basket route, I load the basket view which triggers the following Vue code:
new Vue({
el: '#basket',
ready: function () {
this.fetchBasket();
},
methods: {
fetchBasket: function(){
this.$http.get('api/buy/fetchBasket', function (basketItems) {
this.$set('basketItems', basketItems);
});
}
}
});
This works and I get data returned in the console:
{027c91341fd5cf4d2579b49c4b6a90da:
{id: 1, name: "A Gnarly Tree", price: 15, quantity: 2}}
027c91341fd5cf4d2579b49c4b6a90da:
{id: 1, name: "A Gnarly Tree", price: 15, quantity: 2}
id:1
name:"A Gnarly Tree"
price:15
quantity:2
However, nothing appears in the view itself. I'm trying to use v-for to populate a table:
<tbody>
<tr v-for="item in basketItems">
<td>#{{ item.name }}</td>
<td>#{{ item.price }}</td>
<td>#{{ item.quantity }}</td>
<td>#<button class="btn btn-primary">Update</button></td>
</tr>
</tbody>
What am I doing wrong?
You didn't initialize the basketItems in the data of your vue instance. Try to add:
...
el: '#basket',
data: { basketItems: [] }, // <-- this line
ready: function(){
this.fetchBasket();
},
...
Also edit
this.$set('basketItems', basketItems);
to
Vue.set(this, 'basketItems', basketItems)

access properties in v-repeat over array from objects in vue.js

I have a json-result with 5 categories that I want to loop over with v-repeat. I use the push-method to pass the result to my vue-model.
The setup is 5 different categories to which my records belong. Each category must be shown in a different tab (I removed the category-filter on my results cause is not related to the issue).
The records are showing perfectly (v-repeat="results") and I also get 5 tabs but no values (text neither value).
console.log(this.categories) gives me an array of 5 objects from which I don't succeed to show the properties...what am I doing wrong?
I tried all kinds of things like $value, categorie:categories, ...
JSON-result from my api-call over my categories:
{
status: "success",
data: {
results: {
general: "Algemeen",
metadata: "Meta-data",
facebook: "Facebook",
twitter: "Twitter",
googleplus: "Google+"
}
}
}
The fetching in my Vue-file:
fetchCategories: function(){
this.$http.get('/api/tokens/categories', function (response) {
for(var prop in response.data.results) {
this.categories.push({text: response.data.results[prop], value: prop});
}
});
},
And my view:
<tabs>
<tab v-repeat="category in categories" header="#{{ category.text }}">
<div id="#{{ category.value }}">
<table id="#{{ category.value }}-token-list" class="data-list">
<tr>
<th>id</th>
<th>categorie</th>
<th>naam</th>
<th>slug</th>
</tr>
<tr v-repeat="results" v-class="odd: (index%2!=0)">
<td>#{{ id }}</td>
<td>#{{ category }} </td>
<td>#{{ name }} </td>
<td>#{{ slug }}</td>
</tr>
</table>
</div>
</tab>
</tabs>
EDIT:
I do get my value when I write this:
#{{ categories[0].text }} or #{{ categories[0].value}}
EDIT 2:
it is a problem with the tab-functionality from VueStrap. When I use just a list with #{{ value }} it all work just fine
Seems to be a 0.12 issue. Upgrading to 1.0.x will be the solution!

Categories