What am I missing in rendering JSON object - AngularJS - angularjs

In this Plunker why am I not able to access
{{ cartItem.selectedSeller.registered_name }}
Code
<div ng-repeat="cartItem in cartItems track by $index">
{{ cartItem.selectedSeller }} // I can access this
<h2> Registered Seller Name:</h2>
{{ cartItem.selectedSeller.registered_name }} // but not this
===============================
</div>
from what I know we put [] in case of an array else we can access object attributes using . . I am surely missing some tiny logic here. I want to show Seller name for each cart products.

Your json has an invalid format. Try check it here
"selectedSeller":"{\"registered_name\": \"6bc0317c-0b8b-4b39-96d4-c3377e64acfd_seller\", \"rating\": 1, \"id\": 64, \"delivers_to\": \"[{\\\"city_name\\\": \\\"Pune\\\", \\\"country\\\": \\\"India\\\", \\\"pin_code\\\": \\\"411057\\\"},{\\\"city_name\\\": \\\"Kolkata\\\", \\\"country\\\": \\\"India\\\", \\\"pin_code\\\": \\\"411058\\\"},{\\\"city_name\\\": \\\"Delhi\\\", \\\"cou
by the key selectedSeller you access string but not a object, where presented register_name property
Also, it is a good idea to use json filter, but it depends what version angular you are using.
{{ foo | json }}
Here I can see an advise about parse json, it resolve your problem, also, but I am not recommend for you that way, keep a json backend data in a consistent format and not remap it on the client side through the parsers or some custom methods.

cartItem.selectedSeller is a string, simply parse the string as a JSON like so in your controller:
$scope.cartItems = [];
$http({
method: 'GET',
url: 'data.json'
}).success(function(data) {
data.forEach(function(a){
a.selectedSeller = JSON.parse(a.selectedSeller);
$scope.cartItems.push(a);
});
});

Related

Mapping firebase data in ionic list

I am storing my data in firebase with update() like so
var newKey = firebase.database().ref().push().key;
var updates = {};
updates['metadata/' + newKey] = {
name: $scope.formData.name,
price: $scope.formData.price
};
updates['realdata/' + newKey] = {
name: $scope.formData.name,
price: $scope.formData.price,
date: $scope.formData.date
};
return firebase.database().ref().update(updates)
.then(function(ref){
console.log("added in fb");
}, function(error){
console.log("error " + error)
});
Now on an other page I am pulling the data out of firebase, but I can't seem to map it to my list in my view.
I tried multiple ways to pull the data out and in both ways I can see the data when logging it to the console.
var dbRef = firebase.database().ref('/metadata');
//Method 1
$scope.list = $firebaseArray(dbRef);
/*
Result here in the console is an array with objects
but when setting this in my list, I get the same amount of items pulled out but they are empty
*/
//Method 2 - I prefer this way as per docs it's a best practice
var loadmetadata = function(data){
console.log(data.val().name); // I get the actual name
$scope.list = data.val().name
};
dbRef.on('child_added', loadmetadata);
dbRef.on('child_changed', loadmetadata);
My view is just a simple
<ion-item ng-repeat="listitem in list">
{{ listItem.name }}
</ion-item>
What am I missing? I prefer the second method, if someone can help me achieve this?
The thing is I've found someone with the same problem here on SO, and he was able to solve it with the methods I have above. Here is the link to the question/answer Firebase 3 get list which contain generated keys to ionic list
The only difference I am seeing is that he's sorting the results, but I don't need that currently.
I've just figured it out! Instead of using $firebaseArray, I need to use the $firebseObject method.
$scope.metadataObj = $firebaseObject(dbRef);
and in my view I can do the following:
<ion-item ng-repeat="(key, value) in metadataObj">{{value.name}}</ion-item>
This method contains all the child methodes too. So no need to listen for them separetely.

How can I change a value inside of ng-repeat after the repeat complete?

I have a JSON which provides me a user's working experiences info. But country and city's are provided in a code format (TR,DE etc.)
I am using ng-repeat to pass them into html like this
<div ng-repeat="e in experiences">
<span>{{e.Name}}</span>
<span ng-init="changeCodeToFullName(e.Country)">{{vm.CountryFullName[$index]}}</span>
</div>
I am using ng-init to convert Country Code to full name. changeCodeToFullName is an angular service written by me, Is this a correct method? If it is, I can't access the dom to change CountryFullName value. I tried to access them in JS file like vm.CountryFullName[0]="TEST" but it didn't worked. I need to use e.Country variable after, therefore I can't change the original .e.Country value.
How can I access a variable inside of ng-repeat after ng-repeat completed?
How about using a custom filter:
<div ng-repeat="e in experiences">
<span>{{e.Name}}</span>
<span>{{e.Country | changeCodeToFullName}}</span>
</div>
angular.module('App').filter('changeCodeToFullName', function(YourService) {
return function(country) {
return YourService.getFullCountryName(country)
}
})
Here's an example: http://codepen.io/rustydev/pen/YWyqJB
This is one way of doing it - but this ngInit value won't be reparsed if the list updates. Why not just format the data in the JSON request response - such as:
$http.get("json.json").success(function(data) {
$scope.exeriences = data.map(function(obj) {
//Format results;
if (obj.Country == "DE") {
obj.Country = "Germany"; //etc
}
return obj;
});
});

Efficient way to bind Json to Html?

I am trying to find out a better way to bind my json data to my html .
Json:
$scope.json = { 'one': { 'name': 'level1', 'two': { 'name': 'level2', 'three': { 'name': 'level3' } } } };
Html:
<div ng-controller="myController" >
<div ng-repeat="data in json"> -- (1)
<b>{{data.name}}</b>
<div ng-repeat="data1 in data">
<b>{{data1.name}}</b>
<div ng-repeat="data2 in data1 track by $index"><b>{{data2.name}}</b></div> -- (2)
</div>
</div>
</div>
Pointers : //marked in view
There is no array in my json data , so , is there a better way rather using ng-repeat (sort of traditional for) . Anything like with binding in knockout or templates (i'm not sure How) .
I see there are no duplicates in my json but still to compromise the error i have been using track by $index at the final inner div(if exclude final div i see no error) .
1: There is no array in my json data , so , is there a better way
rather using ng-repeat (sort of traditional for) . Anything like with
binding in knockout or templates (i'm not sure How) .
There is no way to use JSON object for ng-repeat but you can directly use JSON object using . operator for property.
Check below code
<div ng-controller="myController" >
<div>
<b>{{json.one.name}}</b>
<b>{{json.one.two.name}}</b>
<b>{{json.one.two.three.name}}</b>
</div>
</div>
2 : I see there are no duplicates in my json but still to compromise
the error i have been using track by $index at the final inner div(if
exclude final div i see no error).
The reason for error is because you are trying to get index of JSON object which doesn't has index.

How to retrieve nested json object data with Ionic

I am working with the api from The Movie Database. In my Ionic project I was able to make a http request to pull in some data for a movie. However the json object is a nested json object, so I am having some trouble trying to access the genres of a movie:
For the purpose of this question I will display 1 nested json object:
I want to show the information like so -> Genre: Action - Comedy - Drama
My code for the controller is the following:
$scope.init = function(){
MovieService.getMovieById($stateParams.id).then(function(data){
$scope.trending_movie = data;
console.log($scope.trending_movie);
$scope.genres = data.genres;
console.log($scope.genres);
});
}
If I do this bit of code:
$scope.genres = data.genres;
It just returns met the json object of the genres like so:
The thing is now that I am able to read out the genres but because I access the data with a ng-repeat it will show like this:
How to get the genres on 1 line without having to repeat the word "Genre"?
Here is my html code:
<div ng-repeat="genre in genres">
<p class="movie-info-p">Genre: {{genre.name}}</p>
</div>
you should get "Genre:" out of your ng-repeat and if you want your genres to be in the same line, you shouldn't put them in tag.
There is this solution:
<div> Genre:
<div ng-repeat="genre in genres">
<span class="movie-info-p">{{genre.name}}</span>
</div>
</div>
Another solution is to generate this string in the controller with a for loop and send it to the view

WP Rest API Get Featured Image

I am building a relatively simply blog page that uses the WP Rest Api and AngularJs to show the data on the front-end.
On my home page I want to return the title, followed by the featured image, followed by the excerpt. I have pulled the title and excerpt in fine it seems that in the JSON the featured image is a media Id. What is the best way to pull this data in on the fly?
I have seen various things around the internet that use PHP functions but I think the best way to do it is within a angular controller, just looking for some advice on exactly what the controller would be
List View HTML
<ng-include src=" dir + '/form.html?v=2' "></ng-include>
<div class="row">
<div class="col-sm-8 col-lg-10 col-lg-push-1 post">
<div class="row-fluid">
<div class="col-sm-12">
<article ng-repeat="post in posts" class="projects">
<a class="title" href="#/post/{{post.slug}}"><h2>{{post.title.rendered}}</h2></a>
<p ng-bind-html="post.excerpt.rendered | to_trusted"></p>
</article>
</div>
</div>
</div>
</div>
Controller
.controller('listPage',['$scope','Posts', function($scope,Posts){
$scope.refreshPosts = function(){
Posts.query(function(res){
$scope.posts = res;
});
};
$scope.refreshPosts();
// CLEARFORMFUNCTION
$scope.clear = function(){
$scope.$root.openPost = false;
jQuery('#save').modal('hide');
};
// SAVEMODALOPEN/COSE
$scope.openSaveModal = function(){
jQuery('#save').modal('show');
}
$scope.closeSaveModal = function(){
jQuery('#save').modal('hide');
}
// DATEFUNCTION
$scope.datify = function(date){
$scope.date = newDate(date);
return $scope.date.getDate()+'/'+$scope.date.getMonth()+'/'+$scope.date.getYear();
};
}])
You could also modify the JSON response with PHP. This returns just what I need and is very fast (Using _embed is very slow in my experience)
I have the following code in a plugin (used for adding custom post types), but I imagine you could put it in your theme's function.php file.
php
add_action( 'rest_api_init', 'add_thumbnail_to_JSON' );
function add_thumbnail_to_JSON() {
//Add featured image
register_rest_field( 'post',
'featured_image_src', //NAME OF THE NEW FIELD TO BE ADDED - you can call this anything
array(
'get_callback' => 'get_image_src',
'update_callback' => null,
'schema' => null,
)
);
}
function get_image_src( $object, $field_name, $request ) {
$size = 'thumbnail'; // Change this to the size you want | 'medium' / 'large'
$feat_img_array = wp_get_attachment_image_src($object['featured_media'], $size, true);
return $feat_img_array[0];
}
Now in your JSON response you should see a new field called "featured_image_src": containing a url to the thumbnail.
Read more about modifying responses here:
http://v2.wp-api.org/extending/modifying/
And here's more information on the wp_get_attachment_image_src() function
https://developer.wordpress.org/reference/functions/wp_get_attachment_image_src/
**Note: Don't forget <?php ?> tags if this is a new php file!
Turns out, in my case, there is a new plugin available that solves this without having to make a secondary request. See my recent Q:
WP Rest API + AngularJS : How to grab Featured Image for display on page?
If you send the ?_embed param to the query, it will return more information in the response, like images, categories, and author data.
const result = await axios.get(`/wp-json/wp/v2/my-post-type?_embed`);
// Featured Image
result.data._embedded['wp:featuredmedia'][0].source_url;
// Thumbnail
result.data._embedded['wp:featuredmedia'][0]['media_details']['sizes']['medium']['source_url']

Resources