I have a simple JSON file with a "customers" object.
{
"customers": [
{
"firstname": "John",
"lastname": "Doe",
"account": "123456",
"amount": "$121.34",
"period": "13th July - 13th August",
"duedate": "14th September"
},
{
"firstname": "Jack",
"lastname": "Bauer",
"account": "1111222",
"amount": "$142.56",
"period": "11th July - 11th August",
"duedate": "16th September"
}
]
}
Essentially, when a customer visits the page, I want to display his own personal information using Angular JS. So, something like below:
<h2>{{ customers.amount[0] }}</h2>
<p>{{ customers.period[0] }}</p>
<p>{{ customers.duedate[0] }}</p>
my JS file is:
var UtilityApp = angular.module('UtilityApp', []);
UtilityApp.config(['$qProvider', function($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}]);
UtilityApp.controller('mainController', function($scope, $http) {
$http({
method: 'GET',
url: 'https://jsonblob.com/26078b70-6b6f-11e7-a38a-bf689f57642c'
}).then(function (data) {
// create a message to display in our view
$scope.customers = data.customers;
}), function () {
return "Error";
}
});
How can I return all information for customer 1, then customer 2...? Would ng-repeat with a filter be a better approach?
What is a better way to ensure that a customer is looking at his information (and not someone else)? I don't want to use a login here, so I was thinking using a specific URL to visit for customer. Any better idea?
Thanks!
Best and most efficient way would be to get single customer from backend API, so you can ensure security and response is smaller because you don't need to fetch all customers, but if you can't get only one customer then
better would be to filter customer in controller by some key (id, cookie, account etc.)
UtilityApp.controller('mainController', function($scope, $http) {
$http({
method: 'GET',
url: 'https://jsonblob.com/26078b70-6b6f-11e7-a38a-bf689f57642c'
}).then(function (data) {
// create a message to display in our view
$scope.accountId = 'getItSomehow';
$scope.currentCustomer = data.customers.find(x => x.account === $scope.accountId);
}), function () {
return "Error";
}
});
<h2>{{ currentCustomer.amount }}</h2>
<p>{{ currentCustomer.period }}</p>
<p>{{ currentCustomer.duedate }}</p>
ng-repeat with filter would be slowest and vague, don't do it.
Note: have a look at array .find https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find because it is not supported in old browsers.
You can put your customer information like a table using flex or the <table> tag.
If you want to see the information of your customers you should change your code to this.
<h2>{{ customers.amount[0] }}</h2> // <h2>{{ customers[0].amount }}</h2>
<p>{{ customers.period[0] }}</p> // <p>{{ customers[0].period }}</p>
<p>{{ customers.duedate[0] }}</p> // <p>{{ customers[0].duedate }}</p>
Or using ng-repeat
<div ng-repeat="customer in customers">
<h2>{{ customer.amount }}</h2>
<p>{{ customer.period }}</p>
<p>{{ customer.duedate }}</p>
</div>
But if you want to see the information of a specific customer you should pass an ID as a param in the URL for example wit ui-router.
To get the information of the second customer. Example:
http://www.exampleweb.com/customer/2
check out the ui-router module.
https://github.com/angular-ui/ui-router
You are hitting the wrong URL for requesting the json data from json blob. Make the correct url as https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c i.e. https://jsonblob.com/api/jsonBlob/<blobId>.
It will return the JSON data containing customers array then you can use the simple ng-repeat to show the data for both customers. or can extract specific data for the single customers reading the array.
If you want display one particular user at a time then dont use ng-repeat. Simply filter the response data or create a service at server side which give response for particular use by pass parameter.
For now you can filter response
var UtilityApp = angular.module('UtilityApp', []);
UtilityApp.config(['$qProvider', function ($qProvider) {
$qProvider.errorOnUnhandledRejections(false);
}
]);
UtilityApp.controller('mainController', function ($scope, $http) {
$scope.customerAccountId = "123456";
$scope.currentCustomer = null;
$http({
method : 'GET',
url : 'https://jsonblob.com/26078b70-6b6f-11e7-a38a-bf689f57642c'
}).then(function (data) {
$scope.customers = data.customers;
$scope.currentCustomer = $(x) => {
return x.account === $scope.customerAccountId
};
}),
function () {
return "Error";
}
});
And Display currentCustomer details :
<div>
<p>{{ currentCustomer.amount }}</p>
<p>{{ currentCustomer.period }}</p>
<p>{{ currentCustomer.duedate }}</p>
</div>
I have changed the URL of http request from https://jsonblob.com/26078b70-6b6f-11e7-a38a-bf689f57642c to https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c.
Also, I have modified the response object. It have data object which contains your customers object.
You can use some filter condition to identify the customer.
var UtilityApp = angular.module('UtilityApp', []);
UtilityApp.controller('mainController', function($scope, $http) {
$http({
method: 'GET',
url: 'https://jsonblob.com/api/jsonBlob/26078b70-6b6f-11e7-a38a-bf689f57642c'
}).then(function (response) {
$scope.customers = response["data"]["customers"];
//Logic to identify the customer and then bind to $scope.currentCustomer
$scope.account = "123456";
$scope.currentCustomer = response.data.customers.find(x => x.account === $scope.account);
}, function () {
return "Error";
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="UtilityApp" ng-controller="mainController">
<h1>Customer's Info</h1>
<div>
<h2>Account : {{ currentCustomer.account }}</h2>
<p>Amount : {{ currentCustomer.amount }}</p>
<p>Period : {{ currentCustomer.period }}</p>
<p>DueDate : {{ currentCustomer.due_date }}</p>
</div>
<h1>Binding all customer using ng-repeat </h1>
<div ng-repeat="customer in customers">
<h2>{{ customer.amount }}</h2>
<p>{{ customer.period }}</p>
<p>{{ customer.due_date }}</p>
</div>
</div>
//html
<div ng-repeat="obj in customers track by $index">
<h2>{{ obj.amount }}</h2>
<p>{{ obj.period }}</p>
<p>{{ obj.duedate }}</p>
</div>
//controller
$scope.customers = [
{
"firstname": "John",
"lastname": "Doe",
"account": "123456",
"amount": "$121.34",
"period": "13th July - 13th August",
"duedate": "14th September"
},
{
"firstname": "Jack",
"lastname": "Bauer",
"account": "1111222",
"amount": "$142.56",
"period": "11th July - 11th August",
"duedate": "16th September"
}
];
Related
I'm trying to make a simple invitation system, and i want to update a specific field "accepted" from false to true for every invite, when i click on accept button in a template. i'm a beginner in AngularJs
Restfull Api in the url /site/invitations/ :
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Vary: Accept
Content-Type: application/json
[
{
"id": 10,
"user_from_name": "achref97",
"accepted": false,
"deleted": false,
"user_from": 22,
"user_to": 24,
}
]
template.html :
<div class="col-lg-7 col-md-6 no-pd" ng-app="isamm.demo" >
<div class="main-ws-sec">
<div class="posts-section">
<div class="post-bar">
<div class="job_descp" ng-controller="InvitationController">
{% verbatim %}
<div ng-repeat="invite in invitations">
<h3>pour {{invite.user_from}}</h3>
<button ng-click="update()">accept</button>
</div>
{% endverbatim %}
</div>
</div>
</div>
</div>
</div>
JavaScript :
As you can see i retrieve the list of invitations from /site/invitations/, then in the template i create a button with update() function, but i can't continue from there, any help?.
(function(){
'use strict';
var app = angular.module('isamm.demo', []);
app.controller('InvitationController', function ($scope,$http) {
$scope.invitations= [];
$http.get('/site/invitations/').then(function(response){
$scope.invitations= response.data;
});
$scope.update = function (){
// What to do here?
};
});
}());
$scope.update = function (id){
$scope.invitations.filter(invite => {
if (id === invite.id) {
invite.accepted = true;
}
});
};
and pass invite.id to update method in markup
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'm getting an object as the scope. The object looks like this:
And my controller looks like this:
module.controller('ActiveController', ['$scope','$http',
function($scope, $http) {
$http({
method: 'GET',
url: 'http://localhost:8000/api/order/?format=json'
}).then(function successCallback(response) {
console.log("OK Respone");
console.log(response.data);
$scope.orders = response.data;
}, function errorCallback(response) {
console.log("NO Response");
});
}]);
In the browser console, the object looks like this:
I would like some help to loop out and display whole the object in the .html file. My current code that does not work is currently looking like this:
<div ng-controller="ActiveController">
<div ng-repeat="order in orders">
<p>{{ order.id }}</p>
<p>{{ order.created }}</p>
</div>
</div>
I don't think I need to show my "main" .html file, so I'm not posting it.
The problem is in the controller. Try saving objects in $scope.orders
$scope.orders = response.data.objects;
You can fix this in the view and the controller as well:
In View as:
<div ng-controller="ActiveController">
<div ng-repeat="order in orders.objects"> <!-- note the orders.objects -->
<p>{{ order.id }}</p>
<p>{{ order.created }}</p>
</div>
</div>
In Controller as
$scope.orders = response.data.objects;
As rightly suggested by #ddepablo.
It will work fine.
I'm trying to get the user data (such as username) for each user on a row of reviews. I kept my user information (login credentials on another model/controller), so is there a way to access and show the username on the view?
Below is my JSON code:
{
"_id": "56873fc9182b3741059357d0",
"longitude": 113.83507800000007,
"latitude": 22.1533884,
"location": "Hong Kong",
"name": "Hong Kong",
"__v": 0,
"category": "Attraction",
"reviews": [
{
"comment": "Add the comment to the form",
"rating": 3.5,
"userId": 11,
"review_id": "44NL7kkwhy72"
},
{
"comment": "Hello test",
"rating": "3.4",
"userId": "56809c0cf0a264b101a1dd61",
"review_id": "jN7f1iFlQVha"
},
{
"comment": "Hello test ty",
"rating": "3.7",
"userId": "56863c8f2959b4c601fbd9eb",
"review_id": "QcJpw4yopF1q"
}
]
},
//view all reviews for a location
.controller('AllReviews', function($scope, $stateParams, LocFac, UserFac) {
id = $stateParams.id;
LocFac.getLocation(id).then(function(data) {
$scope.locations = data.data;
$scope.reviews = data.data.reviews;
//variables to show information on location reviews
$scope.lengthrev = (data.data.reviews).length;
$scope.locationname = data.data.name;
//addition of values and retrieve the value
$scope.getTotal = function(){
var total = 0;
for(var i = 0; i < $scope.lengthrev; i++){
var review = $scope.reviews[i];
User.getUser(review).then(function(datat) {
$scope.locun = datat.username;
});
total += review.rating;
}
return total;
}
grandtotal = $scope.getTotal();
//get average of all values \
$scope.averagereviews = grandtotal/($scope.lengthrev);
});
})
My location reviews view
<ion-view view-title="All Reviews" class="all_reviews">
<ion-content class="all_reviews">
<h3>{{ locationname }}</h3>
<h3>Average Rating: {{ averagereviews }} <ng-rate-it name="rating" ng-model="averagereviews" resetable="false" read-only="true"></ng-rate-it>/ {{ lengthrev }} Reviews </h3>
<ion-list>
<ion-item data-ng-repeat="location in locations.reviews">
<ng-rate-it name="rating" ng-model="location.rating" resetable="false" read-only="true"></ng-rate-it>
{{ location.userId }}
<h4>{{ location.review_id }}</h4>
<h4>{{ location.comment }}</h4>
</ion-item>
</ion-list>
Considering your two aysnc operations,(one to fetch reviews and another one to fetch usernames) I think this approach will be more suitable.
First fetch the reviews.
Display the reviews.
While displaying the reviews use the UserFac to fetch the username asynchronously using ng-init directive.
I have created a demo plunker as an example with the sample data you provided in question.
Example:
Demo Plunker
app.js
var app = angular.module("app", []);
app.factory('LocFac', function($http) {
var factory = {};
factory.getLocation = function(id) {
return $http({
method: 'GET',
url: 'data.json'
});
}
return factory;
});
app.factory('UserFac', function($http) {
var factory = {};
factory.getUser = function(id) {
return $http({
method: 'GET',
url: 'user.json'
});
}
return factory;
});
app.controller('AllReviews', function($scope, LocFac, UserFac) {
$scope.show = false;
$scope.testClick = function() {
id = "56873fc9182b3741059357d0";
LocFac.getLocation(id).then(function(data) {
$scope.reviews = data.data.reviews;
$scope.lengthrev = (data.data.reviews).length;
$scope.show = true;
});
}
$scope.getUserName=function(review) {
UserFac.getUser(review.id).then(function(user) {
review.userName=user.data.userName;
review.showUserName=true;
});
}
})
HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.4.8" data-semver="1.4.8" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="AllReviews">
<button ng-click="testClick()">Click here</button>
<ul ng-show="show" ng-repeat="review in reviews track by $index" ng-init="getUserName(review)">
{{review | json : spacing}}
<p ng-show="review.showUserName">
{{review.userName}}
</p>
</ul>
</body>
</html>
Explanation:
While iterating the review array in ng-repeat,we pass the review object to the UserFac service to fetch the userName.This service will set the name inside the review object itself.
I've seen so many ways to do this, but most are pretty old and I want to make sure I'm doing this correctly. Right now, the way I'm using isn't working and I feel like I'm missing something.
I'm getting the JSON back fine, I just need to get it to display in a table after I click the button.
Here is the JSON. This is how I'm going to get it from our server, I can't add any "var JSON =" or add any scope like "$scope.carrier" to the data, unless there's a way to add it after I've fetched the data.
{
"carrier":
[
{
"entity": "carrier",
"id": 1,
"parentEntity": "ORMS",
"value": "Medica"
}, {
"entity": "carrier",
"id": 2,
"parentEntity": "ORMS",
"value": "UHG"
}, {
"entity": "carrier",
"id": 3,
"parentEntity": "ORMS",
"value": "Optum"
}, {
"entity": "carrier",
"id": 4,
"parentEntity": "ORMS",
"value": "Insight"
}, {
"entity": "carrier",
"id": 5,
"parentEntity": "ORMS",
"value": "Insight"
}
]
}
Here is the app.js file to bring back the JSON data:
var app = angular.module('myTestApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
var url = 'test.json';
$scope.clickButton = function() {
$http.get(url).success(function(data) {
console.log(data);
});
}
}]);
And then of course the HTML:
<div class="col-lg-12 text-center">
<button type=button class="btn btn-primary load" ng-click="clickButton()">Click!</button>
<table class="">
<tbody ng-repeat="carrier in carriers">
<tr>
<td>
<h3 class="">{{ module.entity }}</h3>
<h3 class="">{{ module.id }}</h3>
<h3 class="">{{ module.parentEntity }}</h3>
<h3 class="">{{ module.value }}</h3>
</td>
</tr>
</tbody>
</table>
</div>
I'm also wondering if I can use the ng-grid to put this in a table. I know they just upgraded it to ui grid so I'm not sure if this is still a feasible approach.
Also, I'm not getting errors, the data just won't display in the table right now. All I know is its returning the data properly, just not displaying in the table.
Any help is appreciated.
I looked at your plunker seems like you need to:
add angular script
wire the app and the controller
your variable in the repeater is wrong, I change it
take a look to this fixed plunker:
http://plnkr.co/edit/TAjnUCMOBxQTC6lNJL8j?p=preview
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
alert(JSON.stringify(returnValue.carrier));
$scope.carriers = returnValue.carrier;
});
}
You never assign the value of the returned array to $scope.carriers.
At the line where you say console.log(data); add this:
$scope.carriers = data.data;
Here is the updated clickButton function (with a variable name change to reduce confusion):
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
$scope.carriers = returnValue.data;
});
};