I have json file called brands.json:
{
"brands": {
"Honda": [
"Accord",
"Civic"
],
"Porsche": [
"Cayenne",
"Cayman"
]
}
}
Im trying to iterate through this list and list the brand(e.g. Honda and Porsche) and render using HTML lists.
<li ng-repeat="brands in items">{{brands}}</li>
JS:
$scope.items= [];
$http.get('brands.json').then(function(response) {
$scope.items =response.data.brands;
});
This code works fine but it displays the arrays inside the brand names e.g. instead if displaying Honda it displays ["Accord", "Civic"]. I want it to display the brand names only.
<li>Honda</li>
<li>Porsche</li>
Try:
<li ng-repeat="(key, value) in items">{{key}}</li>
Quouted from the docs:
(key, value) in expression – where key and value can be any user
defined identifiers, and expression is the scope expression giving the
collection to enumerate.
For example: (name, age) in {'adam':10, 'amalie':12}.
Related
Objective:
Create a hashtagging system against a Product
Models:
Products
Hashtags
ProductTags (join table)
What I'm doing
When I create a new product the following happens:
Product is created
Hashtag is created
ProductTag join is created
The data looks like this:
{
"category_id":2,
"description":"Some description",
"price": 45,
"currency_id": "GBP",
"hashtags":[
{"tag":"tagnumber1"},
{"tag":"tagnumber2"},
{"tag":"tagnumber3"}
]
}
The Product.create code looks like this:
models.Product.create(data, {
include: [
{
model: models.Hashtag,
as: "hashtags",
attributes: models.Hashtag.fields
}
]
});
Issue
When I create the product for the first time with tag: tagnumber1, tagnumber2,tagnumber3. It adds these into the Hashtag table and creates the relation in the ProductTag table.
But when I create another product with the same tag: tagnumber1, tagnumber2,tagnumber3. It still adds these same tags into the Hashtag table.
How?
Is it possible on the second add to still have it INSERT into ProductTags but instead of duplicating the tags in Hashtag to grab the ids if they match?
I have simple model that submits a form that are all from a select I am using an ng-repeat like so:
'Ctrl'
isdom.scheduleOptions = ['Pass', 'N/A'];
'html'
<select ng-model="isdom.isdomForm.isDom101">
<option ng-repeat="option in isdom.scheduleOptions" value="{{option}}">{{option}}</option>
</select>
The person who has built the api end point is asking for the data in this format:
"outcomes": [
{ "itemNo": "is11", "outcome": "Pass" }
,
{ "itemNo": "is12", "outcome": "Pass" }...
How can I do this when my model is like so?
{
"isDom11": "N/A",
"isDOm12": "Pass",...
}
I thought about try to get all the elements in the model that start with isDom and pushing them into an outcomes array that has been modified into objects to copy the format required.
Is there a different way I can use ng-repeat to achieve this?
You could use ng-options for populating the select.
See: ngOptions or select
So it should be something like this:
$scope.isdom.scheduleOptions = [
{ "itemNo": "is11", "outcome": "N/A" }
,
{ "itemNo": "is12", "outcome": "Pass" }
];
<select ng-model="isdom.isdomForm.isDom101"
ng-options="item as item.outcome for item in isdom.scheduleOptions track by item.itemNo"></select>
Try using the (key, value) syntax as given in angular docs.
Key value in ng-repeat
(key, value) in expression –
where key and value can be any user defined identifiers, and expression is the scope expression giving the collection to enumerate.
For example: (name, age) in {'adam':10, 'amalie':12}.
Your example,
isdom.scheduleOptions = {
"isDom11": "N/A",
"isDOm12": "Pass",...
}
<select ng-model="isdom.outcomes">
<option ng-repeat="(itemNo, outcome) in isdom.scheduleOptions" value="{{outcome}}">{{outcome}}</option>
</select>
I am developing a simple hybrid mobile app using the Ionic framework. When you search for a last name, a GET request is sent to retrieve all matching last names, and then displays their corresponding ID's. I am having an issue displaying the returned data from the JSON object.
Below is the html page:
<ion-view view-title="Account" ng-controller="AccountCtrl">
<ion-content>
<div class="list">
<div class="item item-input-inset">
<label class="item-input-wrapper">
<input type="text" placeholder="Search" ng-model="name">
</label>
<button class="button button-small" ng-click="searchUser(name)">
Go
</button>
</div>
</div>
<div>
<ul ng-repeat="user in $results">
<li>{{user.id}}</li>
</ul>
</div>
</ion-content>
Next is the js file that successfully returns a populated JSON object with everything I need.
angular.module('starter.controllers', [])
.controller('AccountCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.searchUser = function (name) {
$http.get('https://notrelevantforthis/searchLastName?=' + name).then(function (response) {
console.log(response.data)
//Assign JSON obj to results to repeat through and display data
$scope.results = response.data;
//To show the actual JSON object is returned
//var jsonStr = JSON.stringify($scope.results);
//document.body.innerHTML = jsonStr;
}, function (error) {
console.log(error)
});
};
}]);
Now the important part is the structure of the JSON object itself. I think this is where I am getting confused. The structure is like the following:
{
"response": {
"totalFound": 275,
"start": 0,
"acc": [
{
"id": [
"1"
],
"first_name": [
"Joe"
],
"last_name": [
"Smith"
]
},
{
"id": [
"2"
],
"first_name": [
"John"
],
"last_name": [
"Doe"
]
}]}
}
My problem is iterating through the JSON object using ng-repeat I think. For some reason none of the data is being displayed, but the object is definitely there when looking at the console. Any help or direction in what I am doing wrong would be much appreciated, as I am new to this and have been trying to find the correct way to do this.
EDIT:
Tried using collection-repeat as well offered by the ionic framework but was getting stack limit errors.
When you're assigning response.data to $scope.results, you're literally assigning the HTTP's response body to it, which is the whole JSON object that you have in your question. You would need to actually point to response.data.response.acc if you wanted to ng-repeat through those accounts.
In your template, it should just be ng-repeat="user in results", without the $ in front of results.
Your JSON object lists the id for each account as an array, I'd recommend just giving the literal value without the array, otherwise in your ng-repeat you'll have to use {{user.id[0]}} to actual print the value without printing the array itself.
I've created an example for you here: http://plnkr.co/edit/GYeF4FzVHl8Og5QTFcDx?p=preview
Here is my Json data
"data": {
"address": {
"postalCode": "112629",
"state": "DL",
"city": "new city",
"streetAddress": "my street"
},
"specialities": [
{
"_id": "577692f7",
"name": "Football",
"description": "game",
"__v": 0
}
]
}
$scope.test = data;
i am fetching data in html by
ng-repeat="mytest in test" than
mytest.address.city // this is working fine
mytest.specialities.name // not printing anything
i am facing the problem in accessing the specialities name i think that is because of specialities is a array but don't know how to get it.
You defined a specialities object with only one array inside
try
mytest.specialities[0].name
Update:
Also you may want to make sure that the array has at least one element, otherwise you mayget a TypeError: Cannot read property 'name' of undefined.
So the code sould look like this:
mytest.specialities.length > 0 ? mytest.specialities[0].name : '(some default value)';
Assuming there will be many specialities you should use ng-repeat to display them all.
<p ng-repeat="s in mytest.specialities"> {{s.name}} / {{s._id}} / {{s.description}} </p>
Yes mytest.specialities is array. JSON has two possible options [ ] - array, { } - object. In this situation we have array of objects - [ { /* object data */ } ] so to get object parameter first go to array element like this ( example getting first element on index 0 ):
mytest.specialities[0].name
second element:
mytest.specialities[1].name
example each:
<div ng-repeat="special in mytest.specialities">
<span>{{special.name}}</span>
</div>
of course before that set mytest to scope like:
$scope.mytest=mytest;//mytest is your data structure
I have trouble understanding how mapping works with knockoutjs.
Pretext:
I have an API, that returns JSON
I want to map that JSON to a list in my view
javascript:
var data = JSON.stringify([
{
"text": "this be some text"
},
{
"text": "some more text here"
}
]);
var viewModel = ko.mapping.fromJSON(data);
var updateData = function(){
var newData = JSON.stringify([
{
"text": "this be some asdfasdfasdf"
},
{
"text": "some more asdfasdfdfdf here"
}
]);
ko.mapping.fromJSON(newData, viewModel);
}
ko.applyBindings(viewModel);
data and newData are in the same format I would be getting my data from API calls. (Just array of objects)
How can i output that data?
<ul data-bind="foreach: whatgoeshere?">
<li data-bind="text: text"></li>
</ul>
Thanks for explaining to me how this magic works ;)
Have a good day
At first you should use fromJS instead of fromJSON as the last one expects a string that contains a json.
Another thing is that you should modify your viewmodel like this:
{ arr: [ { name:'text' }, ... ] }
And type arr in your foreach binding.
If you don't want to modify your model then you may pass $root to your foreach that points to your model used in ko.applyBindings