AngularJS filter search - javascript

I have tried the filter logic from angular to one of the unordered list.
But, the search filter is working after typed 3 characters of the name, sometimes giving wrong search results.
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter :searchString">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
JSON:
{
"People":[
{
"name":"Andrew Amernante",
"rating":3,
"img":"http://www.fillmurray.com/200/200",
"Description":"Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
},
{
"name":"Frank Wang",
"rating":5,
"img":"http://www.fillmurray.com/200/201",
"Description":"Before errors, mails were only pressures. This is not to discredit the idea that a magic is the prose of anelizabeth. This could be, or perhaps some posit the outmost coil to be less than dedal. Some assert that those treatments are nothing more than carp.",
"Likes":[
"Frank",
"Manchester United",
"Football",
"Programming"
],
"Dislikes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
]
},
{
"name":"Sissi Chen",
"rating":5,
"img":"http://www.fillmurray.com/200/202",
"Description":"Aaah! Natural light! Get it off me! Get it off me! Oh, loneliness and cheeseburgers are a dangerous mix. D'oh. Here's to alcohol, the cause of all life's problems.",
"Likes":[
"Cats",
"the beach",
"Chopin",
"Blue things"
],
"Dislikes":[
"Birds"
]
},
{
"name":"Diego Garcia",
"rating":2,
"img":"http://www.fillmurray.com/200/204",
"Description":"Facts are meaningless. You could use facts to prove anything that's even remotely true! I prefer a vehicle that doesn't hurt Mother Earth. It's a go­cart, powered by my ownsense of self­satisfaction. You don't win friends with salad.",
"Likes":[
"Talking Spanish",
"Spanish food",
"Spanish things",
"Football"
],
"Dislikes":[
"Not talking spanish",
"Chopin"
]
},
{
"name":"Fuad Rashid",
"rating":4,
"img":"http://www.fillmurray.com/200/206",
"Description":"Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes":[
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes":[
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
Here is the plnkr code.
Ex: Start typing 'si', you will end up with two results where first one(frank wang) is not correct.
And, this is the reference plnkr where I'm referring for.

You would need to specify which object property, in this case name for the filter to filter against:
<input type='text' ng-model='searchString' placeholder="Search a name..." />
<ul class="nav">
<li class="active" ng-repeat="item in artists.People | filter: { name: searchString }">
<a href ng-click='setSelectedArtist(item)'>{{item.name}}</a>
</li>
</ul>
You would need to set the initial value of searchString to an empty string as well to match against all people when no text has been entered.
$scope.searchString = '';
Here is a Plunker demonstrating the functionality.
Hopefully that helps!

You can create your own customized filter to specify on which property you need to search:
$scope.searchTextByName = function(artist){
if($scope.searchText !== undefined){
if(artist.name.toLowerCase().indexOf($scope.searchText.toLowerCase()) > -1 ){
return artist;
}
}
}
Otherwise, it will match on all JSON value of single people object with your searchText key.

Related

Finding Data from a Json Array Using JavaScript

I have JSON data that is structured like this
[
{
"cs": [
{
"dr": "(i) Two passes at 'A' level in Biology /Zoology /Botany and any other Science subject. (ii) NCE at merit pass level in Biology and any other Science subject. (iii) NCE merit pass level in Agriculture (Double Major).",
"ur": "Five SSCE credits or equivalent in English Language, Chemistry, Biology/Agricultural Science., Mathematics and another relevant subject.",
"us": "Any three subjects from Chemistry, Biology, Agriculture, Physics, Economics, Geography and Mathematics.",
"dc": "BAUCHI accepts: (a) NCE (pass with 5 years teaching experience. (b) N.D at merit pass/lower credit in Biology/Agricultural Science and any other Science subject. (c) Two 'A' Level passes in Biology /Zoology/Botany/Agricultural Science and any other Science subject.",
"uc": "BAUCHI requires Five 'O' level credit passes in English, Mathematics, Arithmetic, Biology, Agricultural Science, Chemistry or General Science and any two subjects. It accepts credit pass in Arithmetic, or General Science or Technical Trades in lieu of Mathematics, or Biology or Physics respectively. UTME SUBJECTS:|BAUCHI requires Mathematics, Biology/Agricultural Science and any other subject.",
"_n": "Agricultural Science And Education",
"_c1": "96",
"_c2": "81",
"_c3": "30",
"_c4": "0",
"_t": "207"
}
...
],
"_n": "Abubakar Tafawa Balewa University, Bauchi",
"_no": "55",
"_c1": "10332",
"_c2": "632",
"_c3": "226",
"_c4": "1",
"_t": "11191",
"_own": "FEDERAL",
"_ab": "BAUCHI",
"_st": "BAUCHI",
"_em": "",
"_pn": "",
"_ws": "atbu.edu.ng",
"_ca": "ADAMAWA, BAUCHI, BENUE, BORNO, GOMBE, TARABA, YOBE"
},
{
"cs": [
{
"dr": "Two A' Level passes in Economics, Accountancy, Business Management, Government and Geography. Candidate must have Science background at 'O' Level.",
"ur": "Five SSCE credit passes to include, English Language, Mathematics, Economics and any other two science subjects from Chemistry, Physics, Biology, Geography, Health Science, Metal Works, Wood Work, Agric Science, Technical Drawing, Nutrition and Food Science.",
"us": "Mathematics, Economics and any one of Chemistry, Physics or Biology.",
"dc": "BAUCHI accepts: (a) Two 'A' level passes in any of Math, Economics, Commerce, Physics, Chemistry, Bio/Agric. (b) ND/HND at lower credit and above.",
"uc": "BAUCHI requires five 'O' level credit passes to include English Language, Mathematics, one Science subject and two Commercial subjects.",
"_n": "Accounting Technology",
"_c1": "490",
"_c2": "19",
"_c3": "8",
"_c4": "0",
"_t": "517"
},
...
],
"_n": "University of Lagos",
"_no": "55",
"_c1": "10332",
"_c2": "632",
"_c3": "226",
"_c4": "1",
"_t": "11191",
"_own": "FEDERAL",
"_ab": "BAUCHI",
"_st": "BAUCHI",
"_em": "",
"_pn": "",
"_ws": "unilag.edu.ng",
"_ca": "ADAMAWA, BAUCHI, BENUE, BORNO, GOMBE, TARABA, YOBE"
}
...
]
i want to search the JSON array using the name of the using a course say "Agricultural Science And Education" then it should the university in this case "University of lagos" and "Abubakar Tafawa Balewa University, Bauchi" and the _ur (requirement)
In your example University of lagos doesn't have a Agricultural Science And Education, try this:
for(let i = 0; i < arr.length; i++){
if(Object.values(arr[i]['cs'][0]).includes('Agricultural Science And Education')){
console.log(arr[i]['_n'])
}
}

Trying to search JSON and display matching results to the screen using grunt and angularJS

I am trying to search through JSON that I load into a variable using angularJS with grunt. I had my app set up with Yeoman. I have done this type of search before without a server, but now that I am trying to use a server, it won't work for me here. I am getting no errors from Chrome, but when I type in the text entry, nothing is returned. What am I doing wrong here?
Here is my view:
<div ng-app="myApp">
<div ng-controller="DatabaseCtrl as result">
<input type="text" ng-model="searchString">
</div>
<ul ng-if="searchString" ng-repeat="i in result.json | filter:searchString">
<li>
<b>{{i.name}}</b> <br><br>
Realm: {{i.realm}} <br>
Description: {{i.description}} <br>
</li>
</ul>
</div>
Here is my controller:
'use strict';
/**
* #ngdoc function
* #name fourthgruntApp.controller:DatabaseCtrl
* #description
* # DatabaseCtrl
* Controller of the fourthgruntApp
*/
angular.module('fourthgruntApp')
.controller('DatabaseCtrl', function () {
this.json = [
{
"name": "Temple of Snow",
"dungeontype": "Temple",
"alignment": "Neutral Good",
"size": "Small",
"agedescriptor": "Millenniums Old",
"hex": "00000",
"realm": "Ernst Chase",
"description": "Temple to the god of Snow. These ancient temples were built long ago by the explorers of the Far Wield when they made their towns and villages. Followers of the gods make pilgrimages to these temples throughout the year."
},
{
"name": "Temple of Memory",
"dungeontype": "Temple",
"alignment": "Neutral Good",
"size": "Meduim",
"agedescriptor": "Millenniums Old",
"hex": "08000",
"realm": "Ernst Chase",
"description": "Temple to the god of Memory. These ancient temples were built long ago by the explorers of the Far Weald when they made their towns and villages. Followers of the gods make pilgrimages to these temples throughout the year. Upon entering the temple, it's said that one can recall information previously thought to be lost. With enough meditation, some priests of Memory have claimed to be able to tap into the memory of others while in the temple."
},
{
"name": "Temple of Sky",
"dungeontype": "Temple",
"alignment": "Neutral Good",
"size": "Diminutive",
"agedescriptor": "Millenniums Old",
"hex": "20000",
"realm": "Karmswald",
"description": "Temple to the god of Sky. These ancient temples were built long ago by the explorers of the Far Weald when they made their towns and villages. Followers of the gods make pilgrimages to these temples throughout the year. ",
"notes": "1. There is a rock near the altar with an engraving that reads “Bow before the holder of the blessed sun, kneel in the glory of the clouds that are carried in it’s arms.” 2. If you commune with the altar here you gain 10 ft of movement speed for 2 days.\n"
}
]
});
Change your ng-app in html,
From
<div ng-app="myApp">
To
<div ng-app="fourthgruntApp">
Also your module should have empty dependencies injected
angular.module('fourthgruntApp',[])
Also take your div which has ng-controller common for ng-repeat and input search
<div ng-controller="DatabaseCtrl as result">
<input type="text" ng-model="searchString">
<ul ng-repeat="i in result.json | filter:searchString">
<li>
<b>{{i.name}}</b>
<br>
<br> Realm: {{i.realm}}
<br> Description: {{i.description}}
<br>
</li>
</ul>
</div>
DEMO

$lookup search Mongodb

Objective
To have an efficient search using references in MongoDB.
Background
I have a Smoothie DB on Mongo. A smoothie is an object with a reference to a Food object and it is represented like:
{
name: "Red Velvet Cake",
ingredients: [{
food_id: "strawberry_raw",
//other really cool fields
},
//other ingredients
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
}
Now, a Food object is represented by the following example:
{
"_id": "strawberry_raw",
"name": "strawberries",
//other really cool fields
}
Problem
With these schemas in mind, I am making sure that a Smoothie object knows all the Food objects that build it. Since each Smoothie object will have at most 6 or 7 food objects, I believe this is the best choice as it follows the MongoDB's Principle of least Cardinality.
However, now I want to allow the following functionalities:
Given a list of ingredient names, return all smoothies that contain at least one of those ingredients
Given a list of ingredient names, return only the smoothies that contain all those ingredients.
And I have no idea how to do it with MongdoDB.
Example
The following examples illustrate what I want.
Imagine I have the following Foods:
let foods = [{
"_id": "strawberry_raw",
"name": "strawberries"
}, {
"_id": "honeydew_melon_raw",
"name": "honeydew melon"
}, {
"_id": "coconut_milk",
"name": "homemade coconut milk"
}];
And the following Smoothies:
let smoothies = [
{
name: "Coco Berry",
ingredients: [
{ food_id: "strawberry_raw" },
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 142"
},
{
name: "Tropical Melon",
ingredients: [
{ food_id: "honeydew_melon_raw"},
{ food_id: "coconut_milk"}
],
preparation: "Mix everything and have fun!",
Source: "Super Smoothies, p. 51"
}];
Given a search with the term "coconuts, strawberry", the functionalities would return:
Coco Berry and Tropical Melon, as both smoothie have at least one of the ingredients (coconut milk)
Coco Berry, as this smoothie has both ingredients, and the second one is missing one ingredient.
What I tried and what i need
I know that to turn a search like "coconuts" return a Food with name "Coconut Milk" I have to index the names in the Food collection, which I did.
I also searched and I found that I will likely need to use $lookup, however, I don't know how to move from that point forward. How do I do it ?
I think there is no need of adding a join or index you can use $regex,let me try my hand,consider smothie as your collection
`
db.collection.find({ingredients : {$elemMatch : {$or :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})
`
Your second query
`
db.collection.find({ingredients : {$elemMatch : {$and :[
{food_id : {$regex : "coconuts")},{food_id : {$regex : "strawberry")}]}}})
`

Cannot create property 'selected' on string 'Information Technology' angularjs

This is my controller
$scope.subjects = ["Computer Security", "Graphics and Multimedia", "Networks", "Computer Science and Engineering", "Game Design", "Programming", "Information Technology", "Software Engineering", "Technology Management", "Telecommunications", "Web Development", "Sociology", "Psychology", "General", "Social Work", "Criminal Justice", "Law and Paralegal", "Public Safety", "Forensic Sciences", "Counseling", "Homeland Security", "Political Science", "Public Administration"];
This is my view where i am binding data
<label class="concentration-label3" ng-repeat="value in subjects">
<input ng-model="value.selected" ng-disabled="subjectCheckedCount == subjectLimit && !value.selected" type="checkbox" name="concentrations" class="concentration-label3__input js-concentration-value" value="{{value}}" data-mixpanel-subject="Design" >
<span class="concentration-label3__title" for="conc1">
{{value}}
<span class="concentration-label3__title__checkmark4"></span>
</span>
</label>
Its giving me the error that 'cannot bind property selected to string
xyz' Please help!!!
subjects is an array of strings, which don't have the property selected that you're trying to bind to your input.
for(var j = 0; j < $scope.subjects.length; j++){
$scope.subjectsArray.push({
'name': $scope.subjects[j],
'value': $scope.subjects[j]
});
}
We must provide ng-repeat an object in order to create any property of
that object later. We cannot create a property of a string. So I converted my array of string into array of objects.

Getting specific information out of JSON file

I am writing an app that requires the user to click on a location and then direct them to the location via Google Maps. I have thousands of locations stored in JSON format. I would like to be able to click the name of the location and have the app pull the coordinates from the file. I have this code so far.
HTML
<body>
<h1>ECC Site Lookup</h1>
<div ng-controller="firstCtrl">
<input type="text" ng-model="search" border="1" />
<ul>
<li ng-repeat="site in SiteLocs |filter : search ">
<a href="http://maps.google.com/?q=" + {{site.Point.coordinates}}> {{site.name}} </a>
</li>"
<li ng-repeat="site in SiteLocs |filter : search "></li>
</ul>
</div>
</body>
I think what is wrong with this is the href portion. Specifically the {{site.Point.coordinates}}
Here is my JS code
(function() {
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
$scope.SiteLocs = [{
"name": "502 Nelson St, Greenville, MS 38701",
"visibility": "0",
"description": "502 Nelson St, Greenville, MS 38701",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-91.05636,33.415485,0"
}
}, {
"name": "242 Blackhawk Trace, Galena, IL 61036",
"visibility": "0",
"description": "242 Blackhawk Trace, Galena, IL 61036",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-90.319778,42.390862,0"
}
}, {
"name": "3747 Ocean Dr, Vero Beach, FL 32963",
"visibility": "0",
"description": "3747 Ocean Dr, Vero Beach, FL 32963",
"styleUrl": "#waypoint",
"Point": {
"coordinates": "-80.358248,27.659094,0"
}];
angular.forEach($scope.SiteLocs, function(location){
// if last 2 characters in string are ",0"
var clength = location.Point.coordinates.length;
if (location.Point.coordinates.substring(clength-2,clength)===",0")
{
location.Point.coordinates = location.Point.coordinates.substring(0,clength-2);
}
});
});
}());
I don't know if it's the best solution, but I would probably make a wrapper function that you would use in place of the raw {{site.Point.coordinates}} in the template.
Make it take 'site' as the argument and return the coordinates that way. It could even be good to have it build the entire link, so that you have all that in the controller rather than the view.
Also couldn't you just do
var clength = location.Point.coordinates.split[',']
and then
if(clength[clength.length-1] === '0')
instead of all the hard-to-follow substring stuff?
The problem is you aren't putting the coordinates inside the href, they are outside the quotes of the href.
<a href="http://maps.google.com/?q=" + {{site.Point.coordinates}}>
should be
<a href="http://maps.google.com/?q={{site.Point.coordinates}}">
It appears you were trying to concatenate strings inside the html which won't work unless it is done inside {{}} expression braces.
<a href="{{'http://maps.google.com/?q=' + site.Point.coordinates}}">
Don't concatenate and (generally) use ng-href :
<a ng-href="http://maps.google.com/?q={{site.Point.coordinates}}">{{site.name}}</a>
Using Angular markup like {{thing}} in an href attribute will make the link go to the wrong URL if the user clicks it before Angular has a chance to replace the {{thing}} markup with its value.
Relevant angularJS documentation
However, it is true that you don't need to use ng-href inside a ng-repeat because it has to be compiled first. You can still use href here.

Categories