How do I map the example in the json output to a string based on the position? It's rather difficult to explain, but I have included my code and further details below:
JSON output
[
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "the team",
"position": 0
},
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "match skills",
"position": 1
},
{
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}",
"example": "defence techniques",
"position": 2
}
]
controller.js
PhraseService.getPhraseExample($scope.phraseId).then(function(dataResponse) {
$scope.phraseExampleList = dataResponse.data;
})
services.js
function PhraseService($http) {
this.getPhraseExample = function(phraseId) {
return $http({
method: 'GET',
url: server + '/api/phrase-example/' + phraseId,
});
}
}
phrase-detail.html
<div class="item item-text-wrap">
<span ng-repeat="e in phraseExampleList">{{ e }}</span>
</div>
Current output
Desired output
You want something as described in https://stackoverflow.com/a/18234317/3856625 Seems that StackOverflow has the same method you need :)
So you would map over the entries you have and just use it to replace the needed.
Related
I'm writing a programme to create a page under a Notion database using the API, but am having trouble getting the multi-select property to work
This is what I have written in properties { } (lines 67-76 of the code in my index.js in my repo)
"multi-select": [
{ "name": tag1},
{ "name": tag2}
],
This is in an async function where tag1 and tag2 are string variables
But when I run the code I get the following error:
'code: validation_error', message: 'body failed validation. Fix one:\n' + .... {"object":"error", ...
(It's too long to paste but that's the gist. I screenshotted the full error here.)
The code works perfectly when I comment these lines out.
I see no reason why this shouldn't work, so I suspect I have done something wrong in my set-up elsewhere, since I'm quite new to coding. The full repo is here - it's not long
Grateful for what I'm sure is probably a quick fix - thank you very much :)
There's a couple things going on with how you're trying to define the the multi select property:
It should be multi_select not multi-select
The body should be an object with an array of options, not just an array. I think you've copied some stuff from an API response which looks a little different.
"Tags": {
"multi_select": {
"options": [
{
"name": tag1,
"color": "red"
},
{
"name": tag2,
"color": "gray"
}
]},
The format for the JSON above seems incorrect, here's an updated one if you're copy/pasting:
{
"Tags": {
"multi_select": {
"options": [
{
"name": "tag1",
"color": "red"
},
{
"name": "tag2",
"color": "gray"
}
]
}
}
}
Edit: I've had some luck with
var items = [];
$.each(response.response.content, function(i, item) {
$("#title").append(item.title + " ");
});
I've connected to an external API and can get everything printed out perfectly in my console log, but can only print it out in JSON format on my HTML page. I'm baffled as to why I can't figure out how to get it to print the same way on my page.
<script>
const settings = {
"async": true,
"crossDomain": true,
"url": "https://learning-objects-v2.p.rapidapi.com/search?keywords=Excel&lang=en&type=video&sort=popularity&model=strict&max=10&page=0",
"method": "GET",
"headers": {
"x-rapidapi-key": "12345678901234567890",
"x-rapidapi-host": "learning-objects-v2.p.rapidapi.com"
}
};
$.ajax(settings).done(function (response) {
$('#demo').append(JSON.stringify(response))
var items = [];
$.each(response.response.content, function(i, item) {
console.log(item);
});
});
</script>
And here is some of the JSON
"response":{
"content":[
{
"title":"Normal distribution excel exercise | Probability and Statistics | Khan
Academy",
"url":"https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description":"(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture":"https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider":[
"YouTube"
],
"bloom":[
"discover"
],
"type":[
"Video"
],
"level":-0.5,
"learningTimeValue":26.07,
"learningTimeUnit":"min"
Here is an example of the console log
{title: "Excel Forecast Function Explained!", url: "https://www.youtube.com/watch?v=nRrZJpG_S7M", description: "This excel video tutorial provides a basic introdu…ted sales forecast in the future. My Website: ...", picture: "https://i.ytimg.com/vi/nRrZJpG_S7M/hqdefault.jpg", provider: Array(1), …}
bloom: ["discover"]
description: "This excel video tutorial provides a basic introduction into the forecast function which can be used to predict a y value given an x value. It could be used to predict the population at a certain year, the value of a car at a given time, or the estimated sales forecast in the future. My Website: ..."
learningTimeUnit: "min"
learningTimeValue: 10.3
level: -0.5
picture: "https://i.ytimg.com/vi/nRrZJpG_S7M/hqdefault.jpg"
provider: ["YouTube"]
title: "Excel Forecast Function Explained!"
type: ["Video"]
url: "https://www.youtube.com/watch?v=nRrZJpG_S7M"
I know I need to assign 's to it, and put it into a loop, but I'm not sure exactly how, and the books I have open aren't helping much. Thank you kindly!
You just need to use keyname to access required values i.e : title,pictures..etc .So , inside your each loop get that values and add them inside generated html and finally append this to your DOM.
Demo Code :
//just for demo ..suppose response variable have your response :
var response = {
"response": {
"content": [{
"title": "Normal distribution excel exercise | Probability and Statistics | Khan Academy ",
"url": "https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description": "(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture": "https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider": [
"YouTube"
],
"bloom": [
"discover"
],
"type": [
"Video"
],
"level": -0.5,
"learningTimeValue": 26.07,
"learningTimeUnit": "min",
}, {
"title": "Normal distribution excel exercise | Probability and Statistics | Khan Academy2222 ",
"url": "https://www.youtube.com/watch?v=yTGEMoaWDCQ",
"description": "(Long-26 minutes) Presentation on spreadsheet to show that the normal distribution approximates the binomial distribution for a large number of trials. Watch the next lesson: https://www.khanacademy.org/math/probability/statistics-inferential/normal_distribution/v/ck12-org-normal-distribution-probl...",
"picture": "https://i.ytimg.com/vi/yTGEMoaWDCQ/hqdefault.jpg",
"provider": [
"YouTube"
],
"bloom": [
"discover"
],
"type": [
"Video"
],
"level": -0.5,
"learningTimeValue": 26.07,
"learningTimeUnit": "min",
}]
}
}
var html = ""
$.each(response.response.content, function(i, item) {
//just for demo ..
html += `<div><img src="${item.picture}"/>${item.title}</div>`
});
$("#somediv").html(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="somediv"></div>
I've made a REST api using Flask which gives a JSON response on http://localhost:5000/api/person giving the id,names and phone numbers of all the people in a SQLite database. http://localhost:5000/api/person/Name_of_person gives the JSON response corresponding to a person's name. I want to use AngularJS to consume the API so that I can output the names of all the people along with their phone numbers.
index.html
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.id }} + ', ' + {{x.name }} + ',' + {{x.phone}}
</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:5000/api/person").then(function (response) {
$scope.myData = response.data.objects;
});
});
</script>
</body>
</html>
Contents of http://localhost:5000/api/person
{
"num_results": 5,
"objects": [
{
"id": 24,
"name": "Name2",
"phone": "9999192938"
},
{
"id": 23,
"name": "Name3",
"phone": "9999192938"
},
{
"id": null,
"name": "Name4",
"phone": "9999192938"
},
{
"id": 21,
"name": "Name5",
"phone": "9999192938"
},
{
"id": null,
"name": "Name6",
"phone": "9999192938"
}
],
"page": 1,
"total_pages": 1
}
I am pretty sure my syntax is correct but I am getting no output for index.html. Can anyone please explain where I am going wrong? Is it maybe because it is on a local server and is unable to retrieve the data?
Please test the api by REST client, if the API returns proper result.
If you are having problem in running the application, please test using firefox browser. For chrome you need to serve the index.html through any server as it blocks file:/// protocol and needs http:// to run properly.
Make sure your API supports CORS. You have to set it in API end (see Flask docs) or else you can use CORS plugin for chrome.
If still problem persists there might be any logical/syntactical error. Please paste/share screenshot of your browser console.
I'm completely rebuilding my website (originally hacked together with Wordpress) using Laravel and AngularJS. It's been a massive learning experience and I think I'm nearly there but for one problem.
On my site 'schemes' (or courses) are made up of 'units' which are made up of 'lessons'. Retrieving this data is fine, using Eloquent I retrieve valid JSON like this made up example...
[
{
"id": "1", //Scheme Id
"title": "Sports",
"description": "This is a Sports course!",
"units": [
{
"id": "1",
"title": "Tennis",
"lessons": [
{
"id": "6",
"title": "Serving"
},
{
"id": "7",
"title": "Hitting the ball with top-spin"
}
]
},
{
"id": "2",
"title": "Athletics",
"lessons": [
{
"id": "1",
"title": "Long Jump"
},
{
"id": "2",
"title": "Hurdling Technique"
}
]
},
{
"id": "4",
"title": "Golf",
"lessons": [
{
"id": "4",
"title": "Pitching"
},
{
"id": "5",
"title": "Putting"
}
]
}
]
}
....
]
Separately I have a simple array of completed lesson ids for a particular user like this...
[2, 6, 8, 9] ///User has completed lessons with ids of 2,6,8 and 9
In my view I'm using nested ng-repeat loops like so...
...
<div ng-controller="SchemesController">
<div ng-repeat="scheme in schemes">
<h1>{{scheme.title}}</h1>
<div ng-repeat="unit in scheme.units">
<h3>{{unit.title}}</h3>
<div ng-repeat="lesson in unit.lessons">
<div>{{lesson.title}}: {{status}}</div>
</div>
</div>
</div>
</div><!--[end of ng-controller="SchemesController"]-->
....
SchemesController (v simple!) looks like this...
var app = angular.module('schemesApp', []);
app.controller('SchemesController', function($scope){
$scope.schemes=jsonData;
});
The problem is I have no idea how to populate the {{status}} field which I want to state simply 'Complete' or 'Incomplete. I investigated whether I could somehow add this info to my original array like this...
"lessons": [
{
"id": "6",
"title": "Serving",
"status": "Complete" //populated somehow
},
{
"id": "7",
"title": "Hitting the ball with top-spin",
}
]
but I got nowhere slowly. Is there a way to do this (I've played around with underscore.js and felt this could help?).
Or do I populate {{status}} from creating and calling a javascript function?!?
ANY help that anyone could offer would be incredible. I'm a school teacher and for some sadistic reason I find a bit of programming/web design a fun use of my spare time so I apologise if this is a stupid question. THANKS in advance!!!
btw if anyone has a better 'title' for this question then please let me know.
I'm assuming you don't need to persist the status back to the database...
This is where you're having the problem:
<div>{{lesson.title}}: {{status}}</div>
You really don't need to store the status in your data model, because it's just used for presentation purposes.
Let's say your array of completed lessons is defined like this:
$scope.completedLessons = [1, 2, 3, 4, 5] // Or however you'd assign it
You need to create a function in your scope like this:
$scope.isLessonCompleted = function(lessonId) {
return $scope.completedLessons.indexOf(lessonId) > -1;
};
Then you need to change the html from above to this:
<div>{{lesson.title}}: {{isLessonCompleted(lesson.id) && 'Complete' || 'Incomplete'}}</div>
If lessons are also a model and each lesson should have a status, which isn't a column/field in your table but is something you'll add logic to determine, you could add a custom model accessor by adding the following to your models/Lesson.php:
// Append custom accessor attributes
protected $appends = ['status'];
public function getStatusAttribute() {
// Add logic here
return 'Complete';
}
This way, when you use Eloquent to retrieve your data, you'll also see a status attribute as part of the object, so you could then access it as usual $lesson->status (PHP) or lesson.status (JS).
For more information, see the official Laravel documentation on accessors and mutators
I have a simple ng-repeat iterating through an array of objects.
The ng-repeat contains a ng-model input element for which I need to use a dynamic value as the array index. Probably very unclear explanation so here is the code :
<div ng-repeat="property in current_data.object_subtype.object_property_type" ng-init="set_input_state()" class="input-group ng-scope disabled">
<span class="input-group-addon">{{property.name}}</span>
<input type="text" placeholder="{{property.name}}" ng-model="current_data.properties[getIndexFromId(current_data.properties, property.object_property_type_id)].value" class="form-control" disabled="disabled">
The problem is that the input stays empty. I've tested some combinations and found this to work :
getIndexFromId(current_data.properties, property.object_property_type_id) == 0
current_data.properties[0].value gives the expected output
So somehow getIndexFromId(current_data.properties, property.object_property_type_id)is not well accepted by Angular or I made a stupid mistake somewhere ...
Does anyone know what's wrong with this?
Thanks!
[edit]
Here is a sample of the data behind all this :
{
"id": 1,
"name": "Robert Smith",
"object_subtype_id": 1,
"object_subtype": {
"id": 1,
"description": "Manager",
"object_property_type": [
{
"id": 1,
"description": "Phone number"
},
{
"id": 2,
"description": "Hair color"
},
{
"id": 3,
"description": "Nickname"
}
]
},
"properties": [
{
"id": 1,
"value": "819-583-4855",
"object_property_type_id": 1
},
{
"id": 2,
"value": "Mauves",
"object_property_type_id": 2
},
{
"id": 3,
"value": "Bob",
"object_property_type_id": 3
}
]
}
From what I've seen of Angular, the content of the attributes are not executed as javascript. It's a custom parsed and executed mini-language that doesn't support complex indexing.
With that said, its probably for the best. Any sufficiently complex logic should be handled by the controller or a service.
function MyController($scope) {
$scope.set_current_data_value = function (current_data, property) {
var index = $scope.getIndexFromId(current_data.properties, property.object_property_type_id);
current_data.properties[index].value = $scope.property_name;
}
}
Then your html would look something like:
<input type="text" placeholder="{{property.name}}" ng-model="property_name" ng-change="set_current_data_value(current_data, property)" class="form-control" disabled="disabled">
You may also be able to use ng-submit if you don't need to update your model in real time.