Angular: how to loop through JSON in controller and display in view - javascript

I am learning a Angular and I'm stuck with one task. I have three parts in my app a View, service and controller,
View look like this:
<body ng-app="ForecastApp">
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
<p class="navbar-brand">Week Forecast</p>
</div>
</nav>
<div class="container-fluid" class="main" ng-controller="MainController">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<h2><span class="label label-info">Search for a City</span></h2>
<div class="input-group">
<input type="text" class="form-control" placeholder="City name...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Go!</button>
</span>
</div>
</div>
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">{{ fiveDay.city.name }}</h1>
<div class="forecast" ng-repeat="day in fiveDay.days">
</div>
</div>
</div>
</div>
</div>
</body>
The service look like this:
app.factory('forecast', ['$http', function($http) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
And the controller look like this:
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
Data for this lesson is take from the rest api from here http://api.openweathermap.org/data/2.5/forecast/city?q=Warsaw&units=metric&mo
How can I go throw all this json resposne and display all the items from the array "list" from this json, for example to look like this:
Date: "2015-06-12 15:00:00"
description: "few clouds"
temp: 26.82
pressure: 1015.2

As I see its simple JSON you can traverse through it using . & whenever required mention index of it to get the value.
Code
$scope.fiveDays = data.list
Markup
<div class="forecast" ng-repeat="day in fiveDays ">
<div>Date : {{dt|date: 'yyyy-dd-MM'}}</div>
<div>description: {{weather[0].description}}</div>
<div>temp: {{main.temp}}</div>
<div>pressure: {{main.pressure}}</div>
</div>
Different angular date filter format

Related

AngularJS iterating through Eventbrite events

My Json file is here.
My HomeController is:
app.controller('HomeController', ['$scope', 'events', function($scope, events) {
events.then(function(data) {
$scope.events = data;
});
$scope.test="success";
}]);
and my html file is:
Home
<h1> {{test}} </h1>
<section class="container" ng-repeat="event in events">
<div class="col-sm-4" >
<div class="card">
<img class="img-responsive" src="https://s3.amazonaws.com/codecademy-content/projects/red-eye-photography/p1.jpg" />
<div class="block">
<h4 class="card-title">{{event.events[0].name.text}}</h4>
<p class="card-text">{{event}}</p>
Go somewhere
</div>
</div>
</div>
</section>
<h1>{{test}}</h1>
My problem occurs when I am trying to loop over "events" array in the JSON file.
I have tried to write "$scope.events = data.events;" in Home controller, " ng-repeat="event in events.events"" or "ng-repeat="event in events[0]"" in html file. This breaks loop and nothing is shown, but if I use "ng-repeat="event in events"" and then variable {{event.events[0].name.text}} in the code later on, it all works fine. I don't understand why there is a problem. It should work fine from my previous experience.
If you declare in your controller
$scope.events = data.data.events;
and have such template:
<section class="container" ng-repeat="event in events">
<div class="col-sm-4">
<div class="card">
<img class="img-responsive" src="https://s3.amazonaws.com/codecademy-content/projects/red-eye-photography/p1.jpg" />
<div class="block">
<h4 class="card-title">{{event.name.text}}</h4>
<p class="card-text">{{event}}</p>
Go somewhere
</div>
</div>
</div>
</section>
it should work. See codepen here

i want to populate my edit form with the data of the selected item

<div class="section" ng-app="ShopMod" ng-controller="myShopsCtrl">
<a class="btn btn-primary btn-fill" href="/addshop">Add a new Shop</a>
<br>
<hr>
<div ng-init="getMyShops()">
<div class="row">
<div ng-repeat="shop in shops">
<div class="col-md-6 col-lg-4 col-sm-12">
<div class="card">
<div class="front">
<div class="cover">
<img src="images/city.jpg" class="img-responsive"/>
</div>
<div class="user">
<img class="img-circle img-responsive" src="images/default-avatar.png"/>
</div>
<div class="content">
<div class="main">
<h3 class="name">{{shop.owner}}</h3>
<h5><i class="fa fa-map-marker fa-fw text-muted"></i> {{shop.address}}, {{shop.state}}</h5>
<h5><i class="fa fa-building-o fa-fw text-muted"></i> {{shop.contact}}</h5>
<h5><i class="fa fa-envelope-o fa-fw text-muted"></i> {{shop.email}}</h5>
</div>
<div class="footer">
<a href="/editshop/:{{shop.id}}">
Edit |
</a>
<a ng-click="manageShop(shop.id)">
Manage |
</a>
<a ng-click="editShop(shop.id)">
Delete
</a>
</div>
</div>
</div> <!-- end front panel -->
</div> <!-- end card -->
</div> <!-- end card-container -->
</div>
</div>
</div>
</div>
</div>
I'm new to sails and angular and i'm having an issue populating my edit form. I have a list of items, code is above. the user clicks the edit link and it takes them to a page,code is below, that will be populated with the data of that selected item.
<div class="section" ng-app="ShopMod" ng-controller="editShopCtrl">
<div class="header text-center">
<h2 style="text-decoration: underline">Edit Shop</h2>
</div>
<div class="content">
<form ng-submit="updateShop()">
<div class="form-group">
<label for="name">Shop Name</label>
<input type="text" class="form-control" ng-model="name" value="{{shop.name}}">
</div>
<div class="form-group">
<label for="address">Shop Address</label>
<input type="text" class="form-control" ng-model="address" value="{{shop.address}}">
</div>
<div class="form-group col-md-6">
<label for="contact">Phone Number</label>
<input type="tel" class="form-control" ng-model="contact" value="{{shop.contact}}">
</div>
<div class="form-group col-md-6">
<label for="email">Shop Email</label>
<input type="email" class="form-control" ng-model="email" value="{{shop.email}}">
</div>
<div class="form-group col-md-6">
<label for="email">State</label>
<select class="form-control" ng-model="state" value="{{shop.state}}">
<option>Lagos</option>
<option>Abuja</option>
</select>
</div>
<div class="col-md-8">
<button type="submit" class="btn btn-fill btn-info">Update Shop</button>
</div>
</form>
</div>
</div>
I know how to get the id of the selected item, and pass it to my back-end controller, my issue is sending that data back from my back-end controller to my form which is basically another view.Below is my function for getting the id from the url,finding the corresponding data and returning it.
editShop:function (req, res)
{
var id = req.param('id');
Shops.findOne({id:id},
function (err, shop)
{
if(err)
{
return res.negotiate(err);
}
return res.send(shop.data)
})
}
Below is the code for how i'm handling the routing
'GET /editshop/:id':{
view:'Shops/editShop',
locals: {
layout: '/Dashboard/layout-admin',
}
}
i would like to know how to go about dealing with this situation.
According to your scenario on click you want to load another page with edit layout. Ejs lets you bind the data you want at backend And so that you can send the data after bind.
But i do it different way.
SAVE All Detail to localStorage of the browser
I am completing only some of your code you can easily see where and what you should do.....
angular.module('ShopMod', [])
.controller('myShopsCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.getMyShops = function (id) {
$http.get('/shops?id=' + id)
.then(function (res) {
if (Array === res.data.constructor)//if res.data is array
$scope.shop = res.data[0];
else //res.data is object.
$scope.shop = res.data;
localStorage.setItem('myShop', JSON.stringify($scope.shop));
}, function (err) {
$scope.shop = {};
console.log(err);
});
}
}]);
In the above...
GET request is made at lcalhost:1337/shops?id=43 (Let shop id is
43).which is a blueprint route(sails make it for you by default
for rapid development).
$scope.shop is initialized with res.data and the same is saved in browsers localStorage by key myShop.Which you can access anytime.(you can see local storage in developer console Resources).
So all you have to do is to load the edit page.
<div class="footer">
<a href="/editshop/">
Edit |
</a>
<a ng-click="manageShop(shop.id)">
Manage |
</a>
<a ng-click="editShop(shop.id)">
Delete
</a>
</div>
Back-end Route for loading edit template.
'GET /editshop/':{
view:'Shops/editShop',
locals: {
layout: '/Dashboard/layout-admin',
}
}
In your edit template.
make ng-init="initializeForm()" at top.
and write controller function.
angular.module('ShopMod', [])
.controller('editShopCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.getMyShops = function (id) {
$scope.shop=JSON.parse(localStorage.myShop);
}
}]);
Putting data from localStorage to current $scope.shop...
This is how i do!I hope it will work for you!

How to parse and use a json object passed from parent page?

I apologize in advance if this has already been answered. I've Googled around for a few hours now, and I still haven't found anything that seems to answer my exact question.
Here is my code:
<ion-content>
<div class="list">
<div style="padding: 0px; margin: 0px;" class="item">
<div class="row"
ng-repeat="x in orders|orderBy:'order_id'| filter:{ paid: '0' } ">
<div class="col left">
{{x.order_id}}
</div>
<div class="col left">
<a ng-href="#/tab/orderdetails?detail={{x.detail}}">订单详情</a>
</div>
</div>
</div>
</div>
</ion-content>
x.detail is the json object i want to pass to the newly opened page "orderdetails.html":
<script id="templates/orderdetails.html" type="text/ng-template">
<ion-view view-title="OrderDetails">
<ion-content class="padding">
<p>Here I want to display order details...</p>
var obj = this.href.split('?')[1];
console.log(obj);
<p>
<a class="button icon ion-home" href="#/tab/home"> Home</a>
</p>
</ion-content>
</ion-view>
</script>
app.js:
.state('tabs.orderdetails', {
url: "/orderdetails",
views: {
'home-tab': {
templateUrl: "templates/orderdetails.html"
}
}
})
I want to know how to parse and use the passed object in "orderdetails.html". Thanks.
You can just pass the data as state params like this below.
<ion-content>
<div class="list">
<div style="padding: 0px; margin: 0px;" class="item">
<div class="row"
ng-repeat="x in orders|orderBy:'order_id'| filter:{ paid: '0' } ">
<div class="col left">
{{x.order_id}}
</div> <div class="col left">
<a ng-href="#/tab/orderdetails/{{x.detail}}">订单详情</a>
</div>
</div>
</div>
</div>
</ion-content>
and recieve it in state params like this below.
.state('tabs.orderdetails', {
url: "/orderdetails/:whateverdata",
views: {
'home-tab': {
templateUrl: "templates/orderdetails.html"
}
}
})
you will get the data in your controller for orderdetails tab as $stateParams.whateverdata

reorder/sort ng-repeat list dynamically

I working on angularjs. I am trying to reorder the ng-repeat list.
There is list of online users.
Users can receive messages anytime. Whenever user receive the message i update the ui and show the recent message under the name.
I am trying to sort the user list based on the users who receive the recent message. The user who receive the messages should come at the top.
Some codes-
Userlist controller:
$scope.$watch('service.get.userList()', function (values) {
var result = [];
angular.forEach(values, function (value) {
processChatService.registerObserverCallback('lastMessage', function () { //i call this event when user receives the message
$scope.$apply(function () {
value.l = processChatService.get.lastMessage(value.u); //returns the recent message
value.time = processChatService.get.lastMessageTime(value.u); //returns time
});
});
value.l = processChatService.get.lastMessage(value.u); //it returns null if user havent recieve message
value.time = processChatService.get.lastMessageTime(value.u);
result.push(value);
});
$scope.users = result;
});
html:
<div ng-repeat="user in users | filter:search"> <a class="list-group-item" ng-click="click(user)" ng-href="">
<div class="row">
<div class="col-xs-2">
<div class="thumb-userlist-sm pull-left mr">
<img class="img-circle" ng-src="{{ user.p }}" alt="...">
</div>
</div>
<div class="col-xs-8">
<div class="message-sender">{{ user.n }}</div>
<div class="message-preview">{{user.l}}</div>
</div>
<div class="col-xs-2">
<div class="pull-right">{{user.time}}</div>
</div>
</div>
</a>
<div class="row">
<div class="col-xs-2"></div>
<div class="col-xs-10">
<div class="line-separator"></div>
</div>
</div>
</div>
What you'll probably want to do is order the ng-repeat:
<div ng-repeat="user in users | filter:search | orderBy: 'time'">
This will order the users on the time property of each user. It's also possible to reverse the sort order with -time.
For more information on the orderBy filter, check the angular documentation.
We can do this by using orderBy.Now it depends upon the requirement.In your case it is time.
<div ng-repeat="user in users | filter:search | orderby:'time'"> <a class="list-group-item" ng-click="click(user)" ng-href="">
<div class="row">
<div class="col-xs-2">
<div class="thumb-userlist-sm pull-left mr">
<img class="img-circle" ng-src="{{ user.p }}" alt="...">
</div>
</div>
<div class="col-xs-8">
<div class="message-sender">{{ user.n }}</div>
<div class="message-preview">{{user.l}}</div>
</div>
<div class="col-xs-2">
<div class="pull-right">{{user.time}}</div>
</div>
</div>
</a>
<div class="row">
<div class="col-xs-2"></div>
<div class="col-xs-10">
<div class="line-separator"></div>
</div>
</div>
</div>

Alternatives to ng-include in angularjs possible?

For some reason , I could not use ng-include in my main page..
Right now i need an alternative solution to ng-include as my product environment(Microsoft Excel Online is not initializing having ng-include on the main page).
Also, I dont want to use ng-view as i have to stick to single route.
FYI, My ng-include url will point to a html template containing its own controller and its scope variables.
Main Page.html
<body ng-app="myapp">
<div class="container-main" ng-controller="MainCtrl">
<div class="container-content">
<div ng-include="content.url"> </div>
</div>
</div>
</body>
controller.js
angular.module('myapp').controller('MainCtrl', function ($scope) {
$scope.content = { url : 'views/templates/mycontent.html'};
});
views/templates/mycontent.html:
<div class="flat-footer" ng-controller="FooterCtrl">
<div class="icon-home" ng-click="settings=false;help=false;gohome()">
</div>
<div class="icon-question" ng-click="settings=false;help=!help;showHelpPreview()" ng-init="help=false">
<div class="arrow-down" ng-show="help"/>
</div>
<div class="icon-cog" ng-init="settings=false" ng-click="settings=!settings;help=false" ng-show="isloggedIn">
<div class="arrow-down" ng-show="settings" />
</div>
<div class="settings-list" ng-show="settings">
<div class="pull-right icon-cancel-circle" ng-click="settings=!settings;help=false"/>
<button type="button" class="btn btn-primary logout" ng-click="settings=!settings;help=false;logout()">Logout</button>
</div>
<div class="help-option" ng-show="help">
<div class="pull-right icon-cancel-circle" ng-click="help=!help;settings=false"/>
<div>
<h1 class="title">//showHelpForUsecase.name//</h1>
<p class="title-description">//showHelpForUsecase.description// </p>
<dl>
<dt class="welcome-title"> //showHelpForUsecase.subtitle// </dt>
<dd class="welcome-definition"> //showHelpForUsecase.subdescription//</dd>
</dl>
</div>
<div class="footer-help-info">
<p class="more-info">More Info</p>
</div>
<div class="help-buttons-group">
<button type="button" class="btn btn-default help-go-back-btn" ng-click="help=!help;settings=false">Back</button>
</div>
</div>
</div>
I want to remove the ng-include in the main page and load the mycontent.html into "div.container-content" element on loading.
Note : Using bind-html-unsafe attribute instead of ng-include not compiling the html template and just binds the html content and resulting inner html content is not bound to its controller at all.
Please help me with a solution for this.
Regards,
Ram
bind-html-unsafe attribute is the possible workaround for ng-include.
Main Page.html
<body ng-app="myapp">
<div class="container-main" ng-controller="MainCtrl">
<div class="container-content">
<div bind-html-unsafe="content"> </div>
</div>
</div>
</body>
angular.module('myapp').controller('MainCtrl', function ($scope) {
$scope.content = { url : 'views/templates/mycontent.html'};
$http.get('views/templates/mycontent.html', {cache: $templateCache}).success(function(data) {
var newScope = $scope.$new();
$scope.content = $compile(data)(newScope);
});
});

Categories