How to pass variables from an array to ng-repeat - angularjs

Problem: I have a list of data that has an ID in each record which I use to make an API call to get more info about this particular item. Problem is - ng-repeat already is looping through my data. How do I pass a different API call's response for each ng-repeat action?
Code:
View:
<div ng-repeat="activity in userActivity">
<div class="row">
<div class="col-md-10 col-md-offset-2">
{[ user.fullname ]} has {[ activity.action ]} to: <a href="#"> {[ post.post ]}<br>
</div>
</div>
Angular Controller:
profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$scope.user = [];
$scope.userActivity = [];
$scope.post = [];
$http.get('/api/user', {params: { id: $routeParams.id }})
.success(function(res){
$scope.user = res.user;
$scope.userActivity = res.user.activity;
$http.get('/api/post', {params: { postID: $scope.userActivity[0].post }})
.success(function(res){
$scope.post = res.post;
})
.error(function(data, status){
console.log(data);
});
})
.error(function(data, status){
console.log(data);
});
}]);
The /api/user's activity from the response looks like this:
"activity": [
{
"post": "123456781",
"action": "agreed"
},
{
"post": "123456782",
"action": "disagreed"
}
]
So can someone please help and point me to the right direction as to how to get the data populated together with the ng-view? Currently, it is just showing the post.post for 123456781 which makes sense but how do I pass the variables to the ng-repeat for such a case?
Thanks in advance

res.user.activity is an array,
so first loop through the $scope.userActivity array an then make an api call for each value in array and then, update the $scope.userActivity array with a new key as post_obj which is the response you will be using in the view.
Then, your controller should be changed to,
profileApp.controller('mainController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams){
$scope.user = [];
$scope.userActivity = [];
$scope.post = [];
$http.get('/api/user', {params: { id: $routeParams.id }})
.success(function(res){
$scope.user = res.user;
$scope.userActivity = res.user.activity;
for(var i=0 ; i < $scope.userActivity.length ; i++)
{
$http.get('/api/post', {params: { postID: $scope.userActivity[i].post }})
.success(function(res){
$scope.userActivity[i].post_obj = res.post;
})
.error(function(data, status){
console.log(data);
});
}
})
.error(function(data, status){
console.log(data);
});
}]);
Then, your view should change to,
<div ng-repeat="activity in userActivity">
<div class="row">
<div class="col-md-10 col-md-offset-2">
{{ user.fullname }} has {{ activity.action }} to: <a href="#"> {{ activity.post_obj }}<br>
</div>
</div
</div>
This userActivity array now contain the post_obj which we got in response corresponding to each post

ng-repeat="activity in userActivity" ng-click="myFunction(activity)"
Create myFunction in controller, which gets only clicked activity.

Related

Parsing Json Array in AngularJS

Iam newbie in angularjs.How to display the json in html using angularjs.Below is the code
var app = angular.module('myapp', []);
app.controller('myctrl', function($scope, $http) {
$http.get("http://localhost:8080/xyz").then(function (response) {
});
});
Reponse is :
[
{
"city": "animal"
},
{
"city": "bird"
}
]
In your controller you should assign your json to a scope:
app.controller('myctrl', function($scope, $http) {
$scope.myArray = [];
$http.get("http://localhost:8080/xyz").then(function (response) {
$scope.myArray = response;
});
});
Then in your view, you can do something like:
<div ng-controller="myctrl">
<ul ng-repeat="obj in myArray">
<li>{{obj.city}}</li>
</ul>
</div>
use ng-repeat like this.
<div ng-repeat="t in test">
<span>{{t.city}}</span>
</div>
plunker here
Use the following code this might help you.
myArray = JSON.parse(response);
for ( var index in myArray ) {
var singleObject = myArray[index];
var keys = Object.keys[singleObject];
for ( var j in keys ) {
console.log("Value of key"+j+"is"+keys[j]+"in Object"+index);
}
}
Here response is a string value.
Try this
Where Records is like this..
{"records":[{"ID":"235","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_02a29.jpg","ImageName":"1.jpg"},{"ID":"236","user_id":"2","project_id":"186","project_cid":"2900669120142632939","imagePath":"media/pano/sv_f0f59.jpg","ImageName":"253.jpg"},{"ID":"239","user_id":"2","project_id":"186","project_cid":"1997319193267363957","imagePath":"media/pano/sv_6536f.jpg","ImageName":"PANOCLOUD_meta.jpg"},{"ID":"240","user_id":"2","project_id":"186","project_cid":"6736594884768838469","imagePath":"media/pano/sv_898ca.jpg","ImageName":"Boscolo Hotel Budapest.jpg"}]}
$http.get("moderatorData.php").then(function (response) {
$scope.panoramas = response.data.records;
});
Then print using like this
<li class="align" ng-repeat="pano in panoramas>
<img ng-src="{{pano.imagePath}}" style="height: 90px;" />
</li>

Ionic retrieving JSON data

I have the following JSON and I am having issues in retrieving the data and displaying it in IONIC. Can someone provide me some guidance ?
JSON
mynews_JsonCallBack({
"items":[
{"headline":"Cat",
"link":"http://www.mynews.com/1",
"description":"Yellow cat",
"pubdate":"Fri, 10 Jun 2016 06:00:19",
"image":"http://www.mynews.com/1.jpg"},
{"headline":"Dog",
"link":"http://www.mynews.com/2",
"description":"Blue dog",
"pubdate":"Fri, 10 Jun 2016 06:00:19",
"image":"http://www.mynews.com/2.jpg"}
]});
Controller
.controller('NewsCtrl', function($http, $scope) {
$scope.news = [];
$http.get('https://www.mynews.com/.json')
.success(function(response) {
$scope.news.push = response.headline;
});
})
Try this
$scope.news = [];
.controller('NewsCtrl', function($http, $scope) {
$http.get('https://www.mynews.com/.json')
.success(function(response) {
$scope.res = response.items[0];
$scope.news.push($scope.res);
})
});
})
<ion-list>
<ion-item ng-repeat="item in news">
{{item.headline}}!
</ion-item>
</ion-list>
try this
<ion list>
<ion item ng-repeat = "title in news">
{{title}}
</ion item>
</ion list>
in your controller
.controller('NewsCtrl', function($http, $scope) {
$scope.news = [];
$http.get('https://www.mynews.com/.json')
.success(function(response) {
$scope.res = response.item;
$scope.res.forEach(function(item) {
$scope.news.push(item.headline);
});
console.log($scope.news);
})
.error(function(response){
console.log(response);
});
});
Try this
$scope.news.push = response[0].headline;
instead of
$scope.news.push = response.headline;

New to the MEAN stack, how to get data?

I'm programming for a college assignment and I've got no idea what I did wrong, so looking for pointers here.
So I'm trying to access events from a database and display them as thumbnails. Where am I going wrong?
HTML Code:
<div class="col-sm-6 col-md-3" ng-repeat="event in EventCtrl.events" ng-controller="EventController as EventCtrl">
<div class="thumbnail tile tile-medium">
<a href="#" data-toggle="modal" data-target="#view-event-modal">
<img id = "eventImg" src="/img/sports.png" alt="Sports">
</a>
</div>
Angular Controller:
angular.module('EventCtrl', []).controller('EventController', function($http) {
$http.get("/events")
.then(function(response) {
this.events = {}
this.events = response.data;
});
});
Node function:
app.get('/events', function(req, res){
eventData = Event.find({}).toArray();
res.render('events', eventData);
});
Your controller should manipulate the $scope, and your view should interact with the scope.
Why don't try something like that
angular.module('EventCtrl', []).controller('EventController', function($scope, $http) {
$http.get("/events").then(function(response) {
$scope.events = response.data;
});
});

Angular ngRepeat fail to extract value from json object

I have a json file "imgae A" which feeds the controller inside-which a console.dir(data) outputs "image D".
The bindiing in the code below is failing to produce the item.name and just outputs blank line in its place "image B".
However, if I change {{item.name}} to just {{item}}, I get "image C"
Is my json wrong or the binding expression is wrong? Thanks
<section>
<ul>
<li ng-repeat="item in menuItems">
<br/>
<p>dummy</p>
{{item.name}}
</li>
</ul>
</section>
Here is the controller as requested in the comments:
var appControllers = angular.module('appControllers', []);
appControllers.controller ('MainMenuCtrl', ['$scope', '$http', function ($scope, $http){
$http.get('js/mainMenu.json').then (function (data){
$scope.menuItems = data;
console.dir(data);
},
function(error){
alert("http error");
});
}]);
menuItems is not the data returned in the http response. It is the http response itself, and you're iterating on its fields (data, status, statusText, etc.)
You probably have something like
$http.get(...).then(function(response) {
$scope.menuItems = response;
});
instead of
$http.get(...).then(function(response) {
$scope.menuItems = response.data;
});

Http request in service successful but not able to show in view

I am working with Ionic and the api of The Movie Database. I wrote a service to make my http request which comes back all good. I get all my outputs in the console.log but for some reason I am still not able to show the data in the view. So I was wondering if I am doing it wrong when it comes to 2 way databinding
Code of my service:
angular.module('starter.services', [])
.service('HotMoviesService', function($http, $q){
var final_url = "https://api.themoviedb.org/3/movie/popular?api_key=XXXX";
var self = {
'hotMovies' : [],
'loadHotMovies' : function() {
var d = $q.defer();
$http.get(final_url)
.success(function success (data){
console.log(data);
self.hotMovies = data.results;
d.resolve('The promise has been fulfilled');
})
.error(function error (msg){
console.error("There was an error retrieving the data " , msg);
d.reject("The promise was not fulfilled");
});
return d.promise;
}
};
return self;
});
My controller.js code:
angular.module('starter.controllers', ['ionic.contrib.ui.hscrollcards', 'starter.services'])
.controller('StartCtrl', function($scope, $http, HotMoviesService) {
$scope.hotmovies = [];
HotMoviesService.loadHotMovies().then(function success (data){
console.log(data);
$scope.hotmovies = HotMoviesService.hotmovies;
},
function error (data){
console.log(data)
});
})
My html code:
<ion-view view-title="The Movie Bank">
<ion-content class="background">
<h1 class="padding titleStart">Welcome to The Movie Bank</h1>
<div class="logo"></div>
<!-- HOT -->
<a class="customHref" href="#/app/hot">
<h1 class="padding customH1">Hot</h1>
</a>
<hscroller>
<ion-scroll direction="x" scrollbar-x="false">
<hcard ng-repeat="hotmovie in hotmovies">
<a href="#/app/hot/{{hotmovie.id}}">
<img ng-src="http://image.tmdb.org/t/p/w92/{{hotmovie.poster_path}}" >
</a>
</hcard>
</ion-scroll>
</hscroller>
</ion-content>
</ion-view>
Here is a screenshot of my console, as you can see everything works fine:
You need hotMovies, note the "m" case:
$scope.hotmovies = HotMoviesService.hotMovies;

Resources