I'm trying to getting items._id value in ng view by using ng-repeat.
occurring all data but i want specific data.
data.json
[ { _id : "td6v9db4514cc4ewew4334",
firstName : 'ayaz',
lastName : 'memon',
items : '[{"_id":"item2","_name":"My Item #4"},
{"_id":"item3","_name":"My Item #4"}]',
totalItems : 3,
totalPrice : 2999.97 } ]
Controller
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json").then((response) => {
console.log(response.data)
$scope.userInfo = response.data
})
})
ng view
<body ng-app="myApp">
<div ng-controller="myCtrl">
<ul ng-repeat="x in userInfo">
<li >{{x}}</li>
</ul>
Here you are using nested json object ie items in userInfo, you can write ng-repeat as,
<body ng-app="myApp">
<div ng-controller="myCtrl">
<ul>
<li ng-repeat="x in userInfo.items">{{x._id}}</li>
</ul>
Note: It will be good to understand if you use ng-repeat in <li></li> instead of <ul></ul>
Try using nested ng-repeat like this:
<ul ng-repeat="user in userInfo">
<li ng-repeat="x in user.items">{{x._id}} : {{x._name}}</li>
</ul>
I'm assuming your http call will return a valid response because the Json data you've given is invalid. The keys need to be in enclosed within " ". I've also structured the the ng-repeat assuming that your response will have multiple objects
Try this,
[{
"_id": "td6v9db4514cc4ewew4334",
"firstName": "ayaz",
"lastName": "memon",
"items": [{
"_id": "item2",
"_name": "My Item #4"
},
{
"_id": "item3",
"_name": "My Item #4"
}
],
"totalItems": 3,
"totalPrice": 2999.97
}]
and you could get your repeated "_id" in the items now in ng-repeat="item in userInfo.items" and with {{item._id}} .
Please correct me if there's any mistake, I'm still new.
Thanks.
I was trying to retrieve string as an object that was a mistake. I used object data instead of string and got result.
This is worked for me:
<ul>
<li ng-repeat="user in userInfo">
<ul>
{{user._id}}
<li ng-repeat="item in user.items">
{{item._id}}
</li>
</ul>
</li>
</ul>
Plunker Example:
http://plnkr.co/edit/hzWdj2IiUI2RytYVUI7m?p=preview
Related
I'm creating an angular webapp, listing different cars in a sidebar and some information about the specific car in a informationbox.
The purpose is to show the right information in the box when clicking the different cars.
I have two different arrays(two API-endpoints), where the first array lists the car name, and the other one got the information about the car. But I have no idea how to connect the objects with the primary key and the foreign key, and how I'm supposed to output the right information after clicking the car.
app.js:
angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
function fetch() {
$http({method : 'GET',url : 'http://*cars*'})
.success(function(data) {
$scope.cars = data;
});
$http({method : 'GET',url : 'http://*information*'})
.success(function(data) {
$scope.information = data;
});
}
fetch();
})
html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
For now all I have done is that I've fetched the data and outputed the cars in the sidebar. But now I've been googling and trying to connect the cars to the information with loops and functions for hours, but stil clueless.
Yes, I'm new to this. Any kind of help would be great! Thanks
You can deal with this with the ng-route. You can do something like :
In your route definition:
.when(/cars/:Id), {
name: 'cars',
templateUrl : 'ayourtemplate.html',
controller : 'yourCtrl'
})
In your html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
The Id will be your key tou will just have to match the right key in your $scope.information
It depends on what information those arrays contains.
If you're sure, that every element corresponds to other, you can just use $index in the html.
<li ng-repeat="name in cars">
{{ name.displayName }}
<p>{{ information[$index] }}</p>
</li>
However, if elements in array aren't ordered, you will have to check primary keys of objects in arrays. Let's assume, that data in arrays looks like this:
cars:
[
{ id: "1", name: "Carrera GT" },
{ id: "2", name: "DB 11" },
... and so on
]
information:
[
{ id: "2", info: "Lorem ipsum" },
{ id: "1", info: "Dolor sit amet" },
...
]
Then I'd suggest using loops and constructing new array using ids.
var carinfo = [];
cars.forEach(car => {
obj["id"] = car.id;
obj["name"] = car.name;
obj["info"] = ""; // Placeholder
info.forEach(c => {
if (c.id === car.id) {
obj["info"] = c.info;
}
});
carinfo.push(obj);
});
$scope.carInfo = carinfo;
Then you can use $scope.carInfo in the html file.
<li ng-repeat="car in carInfo">
{{ car.name }}
<p>{{ car.info }}</p>
</li>
I am trying to display all the books of some series. I used nested ng-repeat and it works well. However, due to some recent changes on layout requirements, I cannot use nested ng-repeat (I want a single list of books). I would expect something like below
<ul>
<li>book1 of series1</li>
<li>book 2 of series 1</li>
<li>book1 of series 2</li>
<li>book2 of series 2</li>
<li>book1 of series 3</li>
<li>book2 of series 3</li>
</ul>
Is there a way to do it with 1 ng-repeat? Or with other approach? (I.e. Array)
Data
var data = {
"records": [
{
"name": "Spectrum Series",
"seriesid": "SpectrumSeries",
"book": [
{
"name": "White Curse",
"bookid": "WhiteCurse",
"image": "book1"
},
{
"name": "Blue Fox",
"bookid": "BlueFox",
"image": "book2"
}
]
}
… other series
]
};
Controller
$scope.serieslist = data.records;
HTML
<div ng-repeat="series in serieslist">
<ul ng-repeat="book in series.book">
<li>
<div>{{series.name}}</div>
<div>{{book.name}}</div>
</li>
</ul>
</div>
Since you want only one list of books, try this
<div ng-repeat="series in serieslist">
<li>
<div>{{series.name}}</div>
<div>{{series.book[0].name}}</div>
</li>
</ul>
</div>
Hope this helps!!!
You need to flatten the array first in your controller into an array with series number and book number, and then use the ng-repeat on the new array.
To do that you can use two angular.forEach on the original array (one for the series and other for the books in each series).
$scope.serieslist = [];
var seriesNumber = 1;
angular.forEach(data.records, function(series) {
var bookNumber = 1;
angular.forEach(series.book, function(book) {
$scope.serieslist.push(
{
seriesNumber: seriesNumber,
bookNumber: bookNumber++,
seriesid: series.seriesid,
name: series.name,
book: book
});
});
seriesNumber++;
});
Here's a plnkr
Working JS fiddle
Just replace element of DOM for use nested ng-repeat
<div ng-app='Your app'>
<div ng-controller='Your controlelr'>
<ul ng-repeat="series in serieslist">
{{series.name}}
<li ng-repeat="book in series.book" >{{ book.name }}</li>
</ul>
</div>
</div>
or
<div ng-app='myApp'>
<div ng-controller='Home'>
<ul ng-repeat="series in serieslist">
<li ng-repeat="book in series.book" >{{ book.name }} of {{series.name}}</li>
</ul>
</div>
</div>
for this result
You can use something like underscorejs to produce a flattened version of your list and then ng-repeat over that. For how you might do that, refer to Karl's answer on this stackoverflow question here: How to flatten with ng-repeat
Controller
$scope.serieslist = data.records;
$scope.flatbooklist = [];
angular.forEach($scope.serieslist, function (series)
{
angular.forEach(series.book, function (book)
{
$scope.flatbooklist.push({seriesname: series.name, seriesid: series.seriesid, bookname: book.name, bookid: book.bookid, bookimage: book.image});
});
});
HTML
<ul ng-repeat="book in flatbooklist">
<li>
<div>{{book.seriesname}}</div>
<div>{{book.bookname}}</div>
</li>
</ul>
I'm trying to iterate through the JSON array and through the ingredients/directions array using ng-repeat. What I have isn't working. Any advice? Thanks!
Controller:
recipeControllers.controller('DetailsController', ['$scope', '$http','$routeParams',
function($scope, $http, $routeParams) {
$http.get('app/data.json').success(function(data) {
$scope.recipe = data;
$scope.whichItem = $routeParams.itemId;
$scope.recipeIngredients = recipe[whichItem].ingredients;
}]);
HTML:
<div class="recipe">
<div class="ingredients">
<ul>
<li ng-repeat="item in recipeIngredients">{{recipeIngredients[whichItem].ingredients}}</li>
</ul>
</div>
</div>
JSON Data:
[
{
"dish":"thai_chicken_satay",
"ingredients": ["chicken", "sauce", "stuff"],
"directions": ["step1", "step2", "step3"]
},
{
"dish":"duck_confit",
"ingredients": ["duck", "confit", "otherstuff"],
"directions": ["step1", "step2", "step3"]
}
]
If you assign $scope.recipeIngredients properly (i.e. whichItem is properly set and maps to an actual object in your JSON data), then $scope.recipeIngredients already points to an array of ingredients (e.g. ["duck", "confit", "otherstuff"]), so to iterate you simply need to do:
<li ng-repeat="item in recipeIngredients">{{item}}</li>
If you need to iterate over the entire data array of recipes, then a nested ng-repeat is needed:
<div ng-repeat="recipe in recipes">
<div>{{recipe.dish}}</div>
<ul>
<li ng-repeat="item in recipe.ingredients">{{item}}</li>
</ul>
</div>
So I'm teaching myself Angular.js. Following a tutorial I found online, I created a RESTful API with Laravel for storing URLS. There's basic authentication set up and currently user id 1 is signed in. I want to grab the JSON that's being returned here in the index function which is all the URLs in the database where the user_id matches the authorized user's id:
public function index()
{
$urls = Url::where('user_id', Auth::user()->id)->get();
return Response::json(array(
'error=> false,
'urls' => $urls->toArray()),
200
);
}
I believe JSON is being returned and when I visit my local site http://readitlater.loc/api/v1/url I get an array of objects. On my index page, I have the ng-app directive being defined as an attribute of the html element:
<html lang="en" data-ng-app="">
I have a script defining a constructor function:
<script>
function mainController($scope, $http)
{
$http.get("http://readitlater.loc/api/v1/url/")
.success(function(response) {$scope.urls = response;});
}
</script>
That readitlater.loc/api/v1/url is my route to the index in my API. And when I type it in the browser I get an array of objects which I'm guessing is the JSON being created. For some reason, I can't get it to display in the browser down here:
<body class="container" data-ng-controller="mainController">
<ul class="list-group">
<li class="list-group-item" ng-repeat="address in urls">
{{ address.url }}
</li>
</ul>
As per your comments above, your $scope.urls has urls object and this object contains url key. so you would change your code as follows
<ul class="list-group">
<li class="list-group-item" ng-repeat="address in urls.urls">
{{ address.url }}
</li>
</ul>
It's often handy to validate the variables you are using contain what you think. You can do a console.log or console.dir when you set the value, but displaying them in the HTML right where you are trying to use them can help with scope problems too. Here I would change your code to this:
<pre>{{urls|json}}</pre>
<ul class="list-group">
<li class="list-group-item" ng-repeat="address in urls">
{{ address.url }}
<br/>JSON: {{address|json}}
</li>
</ul>
This should quickly show you that your $scope.urls object looks like this:
{
error:false,
urls: [
{ description: "A Great Blog", id: 2, url: "fideloper.com", user_id: 1 }
]
}
THAT is your $scope.urls object, so when you repeat over it you will get the properties of the object, 'false' and the array that I assume is what you mean by urls:
// Code goes here
var app = angular.module('MyApp', []);
var ctrl = app.controller('MyCtrl', function($scope) {
$scope.name = "Jason Goemaat";
$scope.urls = {
error:false,
urls: [
{ description: "A Great Blog", id: 2, url: "fideloper.com", user_id: 1 }
]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
<h1>Hello, {{name}}!</h1>
<pre>{{urls|json}}</pre>
<ul class="list-group">
<li class="list-group-item" ng-repeat="address in urls">
{{ address.url }}
<br/>JSON: {{address|json}}
</li>
</ul>
</div>
So if you want $scope.urls to be your array, you can set it directly to the urls property on your return object in the $http call:
$http.get("http://readitlater.loc/api/v1/url/")
.success(function(response) {$scope.urls = response.urls;});
Now your ng-repeat will be iterating over the array as I think you intend...
var app = angular.module('MyApp', []);
var ctrl = app.controller('MyCtrl', function($scope) {
$scope.name = "Jason Goemaat";
$scope.urls = [
{ description: "A Great Blog", id: 2, url: "fideloper.com", user_id: 1 }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
<h1>Hello, {{name}}!</h1>
<pre>{{urls|json}}</pre>
<ul class="list-group">
<li class="list-group-item" ng-repeat="address in urls">
{{ address.url }}
<br/>JSON: {{address|json}}
</li>
</ul>
</div>
I have following problem. I would like to add a controller, whose name is included in the object. Object I receive from ng-repeat.
This is array:
$scope.components = [
{
name: "box",
controller: "BoxCtrl"
}
/*others components*/
];
And this is HTML code:
<ul>
<li ng-repeat="c in components" ng-controller="{{c.controller}}">
{{c.name}}
</li>
</ul>
But I have following
error.
Any ideas how to solve?
The ngController directive expects an instance of a controller but you give him a string.
This should do the job :
In your controller :
$scope.components = [
{
name: "box",
controller: BoxCtrl //Remove the quotes
}
/*others components*/
]
In your view :
<ul>
<li ng-repeat="c in components" ng-controller="c.controller">
{{c.name}}
</li>
</ul>
EDIT: Here is a plunker : http://plnkr.co/edit/sLdZT4UPmgM7Is8SFyrb