Ionic get integer ID from JSON data - javascript

This should be a very simple thing to do. I am building an IONIC app with a JSON data file. The data is something like this.
[
{ "id": 1,
"name": "John",
"type": "male",
"bio": "this is John"
},
{ "id": 10,
"name": "Mary",
"type": "female",
"bio": "this is Mary"
}
]
Now I want to filter by by "type" in the data and then loop the data by "id".
<ion-list ng-repeat="person in people | filter: {'type': 'male'}">
<ion-item href="#tab/people/males/{{ person.id }}">{{ person.name }}
</ion-item>
</ion-list>
The Controller for this is:
.controller('PeopleController', ['$scope', '$state', '$http', function($scope, $state, $http){
$http.get('data/people.json').success(function(data){
$scope.people = data;
$scope.whichPerson = $state.params.id;
}),
}])
This displays the required data of males only by name.
However if I want to see the individual bio using the following code
<div class="card" ng-repeat="person in people | filter: { id: whichPerson }">
<h2>{{ person.name }}</h2>
<p>{{ person.bio}}</p>
</div>
When I click the individual item for each person to display person.bio I get both John and Mary.'
I figured this was because the "id" is 1 and 10 which seems to be parsing as a string to the controller. I tried putting this
"id": "1" and "id": "10"
Did not work. I did this in the controller
$scope.whichPerson = parseInt($state.params.id, 10);
This does not work either. I am totally stumped. How do I get the individual id's from the data? In fact I noticed that I can change the id to 11 or 12 or 13 etc and it still returns both records?
Any help appreciated.

Try to add the comparator :true to your filter as described in the documentation. This forces a strict comparison of the filter value instead of just checking if the data contains it.

Given the above doesn't work, you could try a custom filter by doing:
filter: { id: whichPerson }:sameID
and then in your controller:
$scope.sameID = function(actual, expected) {
return parseInt(actual) === parseInt(expected)
};
Even if this doesn't work, you could then at least debug within the custom filter to see where the comparison is failing

Related

How to put Value from JSON API to Angular Template Directive

iam newbie and i want to ask.
i want to get some value from JSON API (title, course_id, etc), and put the Value to my Template with Directive. so at Index, i can repeat my tempalate with data from the API.
How to get Value from that JSON ?
This my Code :
my API
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://192.168.1.37:8000/api/courses/a/",
"title": "I Love You", <-- I want to put this Value to my Template
"course_id": "1",
"starting_date": "2016-10-03"
}
]
}
Controller demo.js
demo.controller("demo", function($scope, $http) {
$http.get('http://192.168.1.37:8000/api/courses/'). <-- Data From my API
then(function(response) {
$scope.courses = response.data;
});
});
demo.directive("demoItemDirective", function() {
return {
scope : { demoInfo : "=info"},
templateUrl : "/app/demo.tmpl" <-- My Template
};
});
My Template demo.tmpl
<p>{{demoInfo.count}}</p> <-- Works, count Displayed
<p>{{demoInfo.results.title}</p> <-- Not works, title not displayed
My Index.html
<div ng-repeat="group in courses | groupCount:2">
<div ng-repeat="x in group">
<demo-item-directive info="x"></demo-item-directive>
</div>
</div>
It should be
<p>{{demoInfo.results[0].title}</p>
Your result contain an Array of object.
You need to access with index.
According to your post, the result is an array:
"results": [
{
"url": "http://192.168.1.37:8000/api/courses/a/",
"title": "I Love You", <-- I want to put this Value to my Template
"course_id": "1",
"starting_date": "2016-10-03"
}
]
Thus, you can't refer to the title itself, you have to reference the first element:
{{demoInfo.results[0].title}}

AngularJS filter array in array from json data

My data called from a JSON is very simple.
I want to filter all data where the id of events is 13
My json provides from [...] $scope.things = things
[
{
"id":"1",
"title":"title1",
"events":[
{"id":"11",
"events11"},
{"id":"12",
"events12"}
]
},{
"id":"2",
"title":"title2",
"events":[
{"id":"11",
"events11"},
{"id":"13",
"events13"}
]
}
]
I try to display with :
<ion-item collection-repeat="thing in things | filter:{events.id:'13'}">
{{thing.id}}
</ion-item>
Very 1st thing you need to correct you JSON format, like events11, events12 & events13 should be key value pair like such "events": "11", "events": "12" & "events": "13".
Then you could use deep filter like below.
Markup
<ion-item collection-repeat="thing in things | filter:{events: {id:'13'}}">
{{thing.id}}
</ion-item>
Plunkr here
You could filter directly in the controller when instantiating the scope variable:
$scope.things = things.filter(obj => obj.id==='13');
You could try it with ng-if and a helper function:
<ion-item collection-repeat="thing in things" ng-if="getEventInThing(thing, '13')">
{{thing.id}}
</ion-item>
The following function will return the event with the given id, if present:
$scope.getEventInThing = function(thing, eventId) {
return thing.events.find(function(event) {
return event.id===eventId;
});
}
<ion-item collection-repeat="thing in things">
<span ng-repeat="event in thing.events" ng-if="event.id='13'"
{{thing.id}}
</ion-item>
Basically two loops with an ng-if for the inner loop to check if the even's id is 13.

Accessing array of objects in an object using Angular

I am trying to have an array of 30 recipes shown on my view with data from an API call.
// app.js
angular.module('recipeApp', [])
.controller('RecipesCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.mainview = [];
$http.get('/API')
.then(function(response) {
$scope.mainview = response.data;
});
// index.html
<html lang="en" ng-app="recipeApp">
<body ng-controller="RecipesCtrl">
{{mainview}} //this outputs the same data shown on the API call.
// when I try 'ng-repeat' nothing shows up at all
// data from API call (this is just a sample of the data. there is really an array of 30 objects in "recipes")
{
"count": 30,
"recipes": [
{
"publisher": "Closet Cooking",
"f2f_url": "http://food2fork.com/view/35382",
"title": "Jalapeno Popper Grilled Cheese Sandwich",
"source_url": "http://www.closetcooking.com/2011/04/jalapeno-popper-grilled-cheese-sandwich.html",
"recipe_id": "35382",
"image_url": "http://static.food2fork.com/Jalapeno2BPopper2BGrilled2BCheese2BSandwich2B12B500fd186186.jpg",
"social_rank": 100,
"publisher_url": "http://closetcooking.com"
},
{
"publisher": "The Pioneer Woman",
"f2f_url": "http://food2fork.com/view/47024",
"title": "Perfect Iced Coffee",
"source_url": "http://thepioneerwoman.com/cooking/2011/06/perfect-iced-coffee/",
"recipe_id": "47024",
"image_url": "http://static.food2fork.com/icedcoffee5766.jpg",
"social_rank": 100,
"publisher_url": "http://thepioneerwoman.com"
},
When I have {{mainview}} in the html, it shows the same as above, but how can I have it so all 30 recipes are looped in the view? I looked into ng-repeat, but I am very new to Angular and couldn't figure it out. Any information on this would be appreciated.
you can use ng-repeat like this:
<body ng-controller="RecipesCtrl">
<ul>
<li ng-repeat="recipe in mainview.recipes">{{recipe}}</li>
</ul>
</body>
It will generate a li element for every recipe in your array. You can access the properties of a recipe using . as you would in javascript.
{{recipe.publisher}}
Note: ng-repeat works with any elements, I used ul and li for show purposes only.
Something like this may help you:
<ul>
<li ng-repeat="recipe in mainview.recipes">
{{recipe.title}}
<br />
- {{recipe.publisher}}
</li>
</ul>
I think you're looking for a view fragment like:
<div data-ng-repeat="item in mainview.recipes">
<div>
<label>Publisher</label><span>{{item.publisher}}</span>
<div>
<div>
<label>Title</label><span>{{item.title}}</span>
<div>
...
</div>
where ... is whatever else you want to display in the view. Documentation at: https://docs.angularjs.org/api/ng/directive/ngRepeat (though I know you've read it (: )

AngularJS ng-repeat - http.gs retrieving data, but not displaying

I am new to angular and trying to integrate it within my application. I am attempting to use a simple $http.get to a .JSON file, which displaying the matching contents in a ng-repeat
Here my get:
$scope.countries = [];
$http.get('/resources/data/countries-report.json').success(function(data) {
$scope.countries = data.countries;
// alert(JSON.stringify($scope.countries));
console.log(data.countries);
console.log(data.countries.population);
}).error(function(error) {
alert('error');
});
Here's my .JSON file:
{
"firstName" : "Joe",
"surName" : "Bloggs",
"countries" : [
{ "name": "France", "population": "63.1" },
{ "name": "Span", "population": "52.3" },
{ "name": "United Kingdom", "population": "61.8" }
]
}
Here is my HTML:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
When viewing in the browser, all that is displayed is:
has population of
has population of
has population of
It seems as though my code can see there are 3 countries, as when i add or remove from my .JSON file, the list in the HTML modifies accordingly, however, the contents of the .JSON is not displaying.
Have i forgot to return the data from my .get??
** UPDATE *************************
As some have mentioned, my code seems to be correct, i think i know what the problem may be.
My application makes use of a HTML templating structure using Swig which accesses .JSON file using {{ }}.. Could this be causing confusion with Angular?
** UPDATE *************************
If i change:
var app = angular.module("app", []);
to
var app = angular.module('app', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{[{').endSymbol('}]}');
}
);
And:
<li ng-repeat="country in countries">
{{country.name}} has population of {{country.population}}
</li>
To:
<li ng-repeat="country in countries">
{[{country.name}]} has population of {[{country.population}]}
</li>
Then the correct values are displayed.
you have to get the data in the array of object form like
[
{
id:1,
ima:gh.jpg,
data:
[
{
anotherid:1,
my:w,
ki:y
}
]
},
{
id=2,
ima:jh.jpg
}
]

How to filter by object property in angularJS

I am trying to create a custom filter in AngularJS that will filter a list of objects by the values of a specific property. In this case, I want to filter by the "polarity" property(possible values of "Positive", "Neutral", "Negative").
Here is my working code without the filter:
HTML:
<div class="total">
<h2 id="totalTitle"></h2>
<div>{{tweets.length}}</div>
<div id="totalPos">{{tweets.length|posFilter}}</div>
<div id="totalNeut">{{tweets.length|neutFilter}}</div>
<div id="totalNeg">{{tweets.length|negFilter}}</div>
</div>
Here is the "$scope.tweets" array in JSON format:
{{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"},
{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"},
{created_at: "Date", text: "tweet text", user:{name: "user name", screen_name: "user screen name", profile_image_url: "profile pic"}, retweet_count: "retweet count", polarity: "Positive"}}
The best filter I could come up with as follows:
myAppModule.filter('posFilter', function(){
return function(tweets){
var polarity;
var posFilterArray = [];
angular.forEach(tweets, function(tweet){
polarity = tweet.polarity;
console.log(polarity);
if(polarity==='Positive'){
posFilterArray.push(tweet);
}
//console.log(polarity);
});
return posFilterArray;
};
});
This method returns an empty array. And nothing is printed from the "console.log(polarity)" statement. It seems like I am not inserting the correct parameters to access the object property of "polarity."
Any ideas? Your response is greatly appreciated.
You simply have to use the filter filter (see the documentation) :
<div id="totalPos">{{(tweets | filter:{polarity:'Positive'}).length}}</div>
<div id="totalNeut">{{(tweets | filter:{polarity:'Neutral'}).length}}</div>
<div id="totalNeg">{{(tweets | filter:{polarity:'Negative'}).length}}</div>
Fiddle
The documentation has the complete answer. Anyway this is how it is done:
<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>
will filter only age in data array and true is for exact match.
For deep filtering,
<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>
The $ is a special property for deep filter and the true is for exact match like above.
You could also do this to make it more dynamic.
<input name="filterByPolarity" data-ng-model="text.polarity"/>
Then you ng-repeat will look like this
<div class="tweet" data-ng-repeat="tweet in tweets | filter:text"></div>
This filter will of course only be used to filter by polarity
We have Collection as below:
Syntax:
{{(Collection/array/list | filter:{Value : (object value)})[0].KeyName}}
Example:
{{(Collectionstatus | filter:{Value:dt.Status})[0].KeyName}}
-OR-
Syntax:
ng-bind="(input | filter)"
Example:
ng-bind="(Collectionstatus | filter:{Value:dt.Status})[0].KeyName"
You can try this. its working for me 'name' is a property in arr.
repeat="item in (tagWordOptions | filter:{ name: $select.search } ) track by $index

Categories