the first json is coming from the API in get this data by making a http call
[
{
"clientid": 1,
"clientname": "facebook",
"forecasted": 18,
},
{
"clientid": 2,
"clientname": "youtube",
"forecasted": 83,
}
]
i create the second json to update the image on the first json
[
{
"clientid": 1,
"clientname": "facebook ",
"img":"images/21747.jpg"
},
{
"clientid": 2,
"clientname": "youtube",
"img": "images/youtube.svg"
},
]
now i need to macth both json base on the same id, and fill the first json that i coming from the api with images of the second json
app.factory('myFactory', function($http){
return{
client: function(callback){
$http({
method: "GET",
url: "http://www.erek.co.za/api/..",
cache:true
}).then(callback);
},
list: function(callback){
$http({
method: "GET",
url: "data/Client.json",
cache:true
}).then(callback);
}
};
});
app.controller('myController', function ($scope, myFactory) {
myFactory.client(function(response){
var data = response.data;
$scope.myClients = data;
})
myFactory.list(function (response) {
var data = response.data;
$scope.dark = data;
})
});
html
<div ng-repeat="client in myClients>
<a href="#{{client.clientid}}"
<div class="client-project-panel">
<div class="client-logo-container">
<div class="client-logo" >
<img ng-src="{{dark[$index].img}}" alt="{{client.clientname}}">
</div>
<div class="project-forecasted">
<h2 class="forecasted-value">{{client.forecasted}}%</h2>
<p>Complete</p>
</div>
</div>
</div>
</a>
You can use Object.assign method.
let array1=[ { "clientid": 1, "clientname": "facebook", "forecasted": 18, }, { "clientid": 2, "clientname": "youtube", "forecasted": 83, } ]
let array2 = [ { "clientid": 1, "clientname": "facebook ", "img":"images/21747.jpg" }, { "clientid": 2, "clientname": "youtube", "img": "images/youtube.svg" } ]
var expected = array1.map(a => Object.assign(a, array2.find(b => b.clientid == a.clientid)));
console.log(expected);
myFactory.client(function(response){
var data = response.data;
var clientsData = data;
// after you fetch the clients get list of images
myFactory.list(function (response) {
var data = response.data;
var clientImages = {}
for(var i=0;i<data.length;i++){
clientImages[data[i].clientid] = data[i].img
}
$scope.dark = clientImages
$scope.myClients = clientsData
})
})
In your template just refer to {{dark[client.clientid]}}
You might want to wrap your html in ng-if="myClients" so that the content is shown only after the data is fetched
Related
I'm a newbie in Vue-js and really need your help:
In my Django project I have 2 models: Patient and MedCard of this patient. They are connected with a Foreign Key. I want to implement such functionality: on page "Patients" I have list of patients, then when I push on someone's name I want to see his/her MedCard.
This is my code, but when I push on name I get all records for all patients from MedCard model:
Patients.vue:
<div v-for="patient in patients">
<h3 #click="openMedCard(patient.id)">{{patient.surname}} {{patient.name}}</h3>
<p>{{patient.birth_date}}</p>
</div>
<div
<MedCard v-if="med_record.show" :id="med_record.id"></MedCard>
</div>
export default {
name: 'Patient',
components: {
MedCard,
},
data() {
return {
patients: '',
med_record: {
patient: '',
show: false,
}
}
}
and methods from Patient.vue:
methods: {
openMedCard(id) {
this.med_record.patient = id
this.med_record.show = true
}
MedCard.vue:
<template>
<mu-row v-for="med_record in med_records">
<h3>Doc – {{med_record.doc.surname}}{{med_record.doc.name}}</h3>
<p>{{med_record.patient.surname}}</p>
<p>{{med_record.record}}</p>
<small>{{med_record.date}}</small>
</mu-row>
</template>
export default {
name: 'MedCard',
props: {
id: '',
},
data() {
return {
med_records: '',
}
},
methods: {
loadMedCard() {
$.ajax({
url: "http://127.0.0.1:8000/api/v1/hospital/med_card/",
type: "GET",
data: {
id: this.id,
patient: this.patient
},
success: (response) => {
this.med_records = response.data.data
}
})
}
}
}
loadMedCard() gives me info from all MedCards in JSON like this:
{
"data": {
"data": [
{
"id": 1,
"patient": {
"id": 1,
"surname": "KKK",
"name": "KKK",
"patronymic": "LLL",
"birth_date": "1999-07-07",
"sex": "F",
"phone": "no_phone",
"email": "no_email"
},
"doc": {
"id": 3,
"surname": "DDD",
"name": "DDD",
"patronymic": "DDD",
"education": "d",
"category": "2",
"sex": "m",
"phone": "no_phone",
"email": "no_email"
},
"record": "test text",
"date": "2020-06-09"
}...]
I'll be grateful for any help!
So the API returns you multiple patients's data while you're asking it for just one exact patient. There must be something wrong with the API with the filtering in first place. So you can filter your data on the client side, in your MedCard.vue component. First this component have to show data for one patient only, so the v-for="med_record in med_records" is not needed. Your med_records property can become just an object not an array:
data() {
return {
med_record: {},
}
}
And in the success resolve method of your API call you can filter only the data you need and store it in med_record
success: (response) => {
this.med_records = response.data.data.find((patient)=> { return patient.id === this.id})
}
If you want to store all the data in the med_records, then you can create computed property and apply the same filtering there.
I hope this helps.
This is on of tough task that am facing in my school. am totally new to angularJs. i need to fetch one image out of all retrieved images from the database. And then when i refresh the page the next image want to appear.
for an example first "banner.jpg" appear when i refresh the page "banner1.jpg" want to appear. can anyone help me to do solve this problem. please.
This is my retrieved Json
{
"id": 1,
"path": "Content/Banner/banner.jpg"
},
{
"id": 2,
"path": "Content/Banner/banner1.jpg"
},
{
"id": 3,
"path": "Content/Banner/banner2.jpg"
},
{
"id": 4,
"path": "Content/Banner/banner3.jpg"
},
my angular controller.
appGM.controller('bannerCtrl', ['$scope', '$http', 'urls', function ($scope, $http, urls) {
var request = $http({
method: 'GET',
url: urls.api + 'Banner/Banners'
}).success(function (data, status) {
console.log(data);
console.log(JSON.stringify(data));
console.log(JSON.parse(JSON.stringify(data)));
$scope.BBanner = angular.fromJson(data);
})
.error(function (error) {
$scope.status = 'Unable to load dog images: ' + error.message;
console.log($scope.status);
});
And its my Html
<div class="row">
<div class="col-sm-3 sidenav" ng-repeat="d in BBanner">
<img ng-src="{{d.path}}">
</div>
you can use localstorage to store the in in the first time. After you refresh the page increment the value and save it to the same local storage and so on.
run this Demo multiple time to see the id change.
controller
if(!localStorage.getItem("uID")){
var s = {"id":1};
localStorage.setItem("uID", JSON.stringify(s))
}
$scope.data = [{
"id": 1,
"path": "Content/Banner/banner.jpg"
},
{
"id": 2,
"path": "Content/Banner/banner1.jpg"
},
{
"id": 3,
"path": "Content/Banner/banner2.jpg"
},
{
"id": 4,
"path": "Content/Banner/banner3.jpg"
}]
var item = localStorage.getItem("uID")
item = JSON.parse(item);
alert("Id = " + item.id)
item.id = item.id +1 ;
localStorage.setItem("uID", JSON.stringify(item))
$scope.clear = function(){
localStorage.removeItem("uID");
}
updated
add this to check the image. check the demo again
var item = localStorage.getItem("uID")
item = JSON.parse(item);
var obj = $scope.data.find(function(o){
return o.id === item.id
})
// add this lines
$scope.image =(obj)? obj.path : "invalid id";
if(item.id == 4){
localStorage.removeItem("uIDs");
item.id = 0;
}
item.id = item.id +1 ;
What am I doing wrong with my bindings? I simply get [object HTMLElement] returned for each one.
Please note this is a pared-down version and I will be wanting to access the full range of the JSON values.
Fiddle:
https://jsfiddle.net/0416f0s7/2/
Code:
<div data-bind="text: intro"></div>
function ViewModel(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function(story) {
return story.stories;
}));
};
$.getJSON('data.json', function(data) {
window.storyViewModel = new ViewModel(data.stories);
ko.applyBindings(window.storyViewModel);
});
JSON (filename data.json):
{
"stories": [
{
"intro": "Hi",
"outro": "Bye",
"elements": [
{
"title": "Title 1",
"image": "img/image1.jpg",
"paragraph": "Wordswordswords"
},
{
"title": "Title 2",
"image": "img/image2.jpg",
"paragraph": "More wordswordswords"
}
]
}
]
}
Your html change to
`<div data-bind="foreach:stories">
<div data-bind="text: intro"></div>
</div>
your code change to
function test(stories) {
var self = this;
self.stories = ko.observableArray(ko.utils.arrayMap(stories, function (story) {
return story;
}));
}
I'm new to Meteor and trying to figure out this issue I have.
I'm trying to load data from the Lessons collection based on the route being passed. e.g if /courses/level1/lesson1/1a is passed then show data
Unfortunately this doesn't work.
Am I on the right path or is there a better way of doing this?
Collection
{
"_id": "YSgr3fvjpEBn7ncRa",
"courseId": "level1",
"lesson": [
{
"lessonId": "lesson1",
"freeLesson": true,
"title": "Lesson 1",
"eachLesson": [
{
"eachLessonId": "1a",
"title": "This is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1b",
"title": "That is (masculine)",
"video": "839843"
},
{
"eachLessonId": "1c",
"title": "This is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1d",
"title": "That is (feminine)",
"video": "839843"
},
{
"eachLessonId": "1e",
"title": "Getting to know you",
"video": "839843"
}
]
}
]
}
Routes
Router.route("courses/:courseId/:lessonId/:eachLessonId", {
path:"/courses/:courseId/:lessonId/:eachLessonId",
layoutTemplate: "layoutLessons",
template:"lessons",
onBeforeAction:function(){
var currentUser = Meteor.userId();
if (currentUser) {
Session.set('courseId', this.params.courseId);
Session.set('lessonId', this.params.lessonId);
Session.set('eachLessonId', this.params.eachLessonId);
this.next();
} else {
Router.go('/')
}
},
});
Template helper
Template.lessons.onCreated(function(){
Meteor.subscribe('listLessons');
});
Template.lessons.helpers({
currentLesson: function() {
var currentLesson = Session.get('eachLessonId');
return Lessons.find({"lesson.eachLesson.eachLessonId" : currentLesson});
},
});
HTML
{{#each currentLesson}}
{{title}}
{{video}}
{{/each}}
Instead of storing courseId, lessonId and eachLessonId as Session values, you could use the Iron Router's waitOn and data option.
For example, you could rewrite your route as follows:
Router.route('/courses/:courseId/:lessonId/:eachLessonId', {
name: 'lessons',
layoutTemplate: 'layoutLessons',
template: 'lessons',
onBeforeAction: function() {
let currentUser = Meteor.user();
if (currentUser) this.next();
else Router.go('/');
},
data: function() {
var doc = Lessons.findOne({
"courseId": this.params.courseId,
"lesson.lessonId": this.params.lessonId,
"lesson.eachLesson.eachLessonId": this.params.eachLessonId
});
if (doc) {
var lesson = {};
var lessonId = this.params.eachLessonId;
_.each(doc.lesson, function(i) {
lesson = _.find(i.eachLesson, function(j) {
return j.eachLessonId == lessonId;
});
});
return lesson;
}
return {};
},
waitOn: function() {
return [
Meteor.subscribe('lesson', this.params.courseId, this.params.lessonId, this.params.eachLessonId)
];
}
});
This should set the data context to the requested eachLesson object. However, you may consider setting the data context to a document in the Lessons collection and then just picking certain eachLesson objects. In addition, you should create a publish function which returns just the requested Lessons document and not all of them, like you probably do now in your listLessons publication. You can pass all IDs as arguments to the corresponding publish function.
I' very new to json, I can't seem to access it right variables.
I'm trying to get "username" for example, so that I can create mocks for AngularJS project.
$httpBackend.expectGET('user.json').
respond(Users[ { Username: "bjarnipolo"}, { Username: "yolo"} ]);
{
"Users":[
{
"UserId":1,
"Username":"bjarnipolo",
"Password":null,
"FirstName":"Bjarni Póló",
"LastName":"Súkkulaðisson",
"Ssn":"2412813539",
"Email":"bjarnip08#ru.is",
"Phone":"6903066",
"Roles":"Stjornandi",
"JobTitle":"Scrum Master",
"ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
"IsActive":true
},
{
"UserId":2,
"Username":"yolo",
"Password":null,
"FirstName":"Brynjólfur YOLO",
"LastName":"Hermannsson",
"Ssn":"0106752040",
"Email":"Binni#example.com",
"Phone":"8995555",
"Roles":"Notandi",
"JobTitle":"Team member",
"ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
"IsActive":true
}
]
}
I think I found a solution to get what you want.
You can use new Request.JSON. The request should look like this :
new Request.JSON({
url: '/echo/json/',
data: {
json: JSON.encode({
"Users":[
{
"UserId":1,
"Username":"bjarnipolo",
"Password":null,
"FirstName":"Bjarni Póló",
"LastName":"Súkkulaðisson",
"Ssn":"2412813539",
"Email":"bjarnip08#ru.is",
"Phone":"6903066",
"Roles":"Stjornandi",
"JobTitle":"Scrum Master",
"ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
"IsActive":true
},
{
"UserId":2,
"Username":"yolo",
"Password":null,
"FirstName":"Brynjólfur YOLO",
"LastName":"Hermannsson",
"Ssn":"0106752040",
"Email":"Binni#example.com",
"Phone":"8995555",
"Roles":"Notandi",
"JobTitle":"Team member",
"ImageUrl":"http://us.cdn4.123rf.com/168nwm/nruboc/nruboc0802/nruboc080200034/2557282-a-small-cute-dog-playing-basketball-over-a-black-background.jpg",
"IsActive":true
}
]
}),
},
onSuccess: function(response) {
var jsonObj = response;
alert(jsonObj.Users[1].Username);
jsonObj.Users[1].Username = "dsds";
alert(jsonObj.Users[1].Username);
}
}).send();
Here is the jsFiddle.