Angular create element if another is non-existent - javascript
I have a list of states (Florida, Alabama ...) and I want to create named anchors above the first occurance of the first letter.
Letter Links
<nav>
<ul class="letters">
<li ng-repeat="letter in locations.getLetters()">
{{letter}}
</li>
</ul>
</nav>
States
<nav>
<ul class="locations">
<li ng-repeat="state in locations.states">{{state.state}}
<a ng-if="" id="{{state.state.charAt(0)}}">fgsdf</a>
<ul>
<li ng-repeat="city in state.cities">
<a href>{{city.name}}</a>
</li>
</ul>
</li>
</ul>
</nav>
I am stuck at <a ng-if="" id="{{state.state.charAt(0)}}">fgsdf</a>
I have tried ng-if="!document.getElementById(state.state.charAt(0))" and that doesn't work. Does anyone have any suggestions as to how I should go about this?
Update
I've considered using angular's built-in filters to filter the states in ngRepeat. When a user clicks A, only the states starting with A should show. This seems like a much cleaner and more intuitive approach and will improve UX.
You can try this approach
let's assume you have the input as a simple array of strings. before placing it in the controller, we can group states by the first letter of each state using a simple object (the letter is a key, the value is an array of strings)
http://jsfiddle.net/q2y93ym7/1/
html:
<body ng-app="HelloApp" ng-controller="Controller" class="container">
<div class="well">
{{letter}}
</div>
<div ng-attr-id="{{letter}}" ng-repeat="(letter,states) in letters">
<h1>{{letter}}</h1>
<h2 ng-repeat="state in states">{{state}}</h2>
<hr>
</div>
</body>
js:
angular.module('HelloApp', [])
.controller('Controller', function ($scope) {
var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyomin'];
// Let's prepare the input
var letters = $scope.letters = {};
states.forEach(function (state) {
var letter = state.charAt(0);
if (!letters[letter]) {
letters[letter] = [];
}
letters[letter].push(state);
});
})
EDIT:
As #DRobinson says, nothing guarantees keys of an Object will be sorted. therefore you can try using this great approach / instead an Object, use an array
added <h1>{{letter}}</h1>, thanks #Tony
That won't work because document is not part of the current scope.
Here's what you can do:
Controller:
$scope.elementExists = function (selector) {
return typeof $document.getElementById(selector) !== 'undefined';
}
Html:
<a ng-if="!elementExists('elementId')">Link</a>
Don't forget to add $document as a dependency of your controller.
Related
Jquery dropdown list from demo selenium solution using Python
I creating a solution to a task from http://demo.seleniumeasy.com/jquery-dropdown-search-demo.html using python and selenium framework. I just want to click on every element from a dropdown list using for loop. I tried several ways and it is my final code. I am pretty sure that is not optimal and I would like to get Your feedback about how to improve this. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select from selenium.webdriver.remote.webelement import WebElement from selenium.common.exceptions import NoSuchElementException import time def select_jquery(select_list: WebElement, elements_list: list[str]) -> None: for element in elements_list: select_list.click() try: if element == 'Blank': element = driver.find_element(By.XPATH, "//li[#role='treeitem']") else: element = driver.find_element(By.XPATH, f"//li[text()='{element}']") except NoSuchElementException: select_list.click() element = driver.find_element(By.XPATH, f"//li[text()='{element}']") element.click() time.sleep(1) states_list = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District Of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'] countries_list = ['Australia', 'Bangladesh', 'Denmark', 'Hong Kong', 'Blank', 'India', 'Japan', 'Netherlands', 'New Zealand', 'South Africa', 'United States of America'] us_outlying_territories_list = ['American Samoa', 'Guam', 'Northern Mariana Islands', 'Puerto Rico', 'United States Minor Outlying Islands', 'Virgin Islands'] driver = webdriver.Chrome() driver.get("https://demo.seleniumeasy.com/jquery-dropdown-search-demo.html") # Drop Down with Search box select_countries = driver.find_element(By.XPATH, "//span[#class='select2-selection select2-selection--single']") select_jquery(select_countries, countries_list) # Select Multiple Values select_states = driver.find_element(By.XPATH, "//input[#class='select2-search__field']") select_jquery(select_states, states_list) # Drop Down with Disabled values ABSOLUTE_XPATH = "/html[1]/body[1]/div[2]/div[1]/div[2]/div[3]/div[1]/div[2]/span[1]/span[1]/span[1]/span[1]" select_us_territories = driver.find_element(By.XPATH, ABSOLUTE_XPATH) select_jquery(select_us_territories, us_outlying_territories_list) # Drop-down with Category related options select_file = Select(driver.find_element(By.XPATH, "//select[#name='files']")) for option in select_file.options: option.click() print(f"Option {option.text} clicked") time.sleep(1) time.sleep(5) My thoughts: I wanted to create a function to iterate over every element of a jquery dropdown list but I found that html //span disappears after I click on the element (it is present only when list is opened, I couldn't find ''Select US Outlying Territories :' using relative XPATH, only absolute PATH has worked, I didn't want to use Select objects despite the fact that they were available 'Blank' stands for white option on first dropdown list
Why is my sorting algorithm not sorting correctly?
I was given this sorting function in the best answer to a question I posted. It worked on the example data, but does not appear to work on my actual data and I am not sure why. My data can be see here: JSON It's an object of objects like this: "Montana": { "superiors": [ "Massachusetts", "Oklahoma", "New Mexico" ], "inferiors": [ "North Carolina" ] } It exists to instruct the sorting function. Here, Montana must be higher up in the list than North Carolina. But below Massachusetts, Oklahoma, and New Mexico (nothing to do with geography by the way). Note to avoid confusion: This has nothing to do with the order of object keys. But the sorting isn't being followed precisely (it's mostly followed though). For example, states['North Carolina'].superiors.includes('Ohio') === true so why is 'Ohio' listed beneath 'North Carolina'? fetch('https://api.npoint.io/7571e85ef470a2a7f189') .then(data => data.json()) .then(states => { function mySort(arr) { const scores = Array(arr.length).fill(0); for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr.length; j++) { if (i === j) continue; const a = arr[i]; const b = arr[j]; if (states[a].inferiors.includes(b) || states[b].superiors.includes(a)) scores[j]++; else if (states[b].inferiors.includes(a) || states[a].superiors.includes(b)) scores[i]++; } } // Sort arr by scores: return arr.map((val, i) => [scores[i], val]) .sort((a, b) => a[0] - b[0]) .map(pair => pair[1]); } const names = Object.keys(states); console.log(mySort(names)); /* [ 'Tennessee', 'Oklahoma', 'Alaska', 'Wisconsin', 'Arkansas', 'New York', 'Nevada', 'Montana', 'Georgia', 'Massachusetts', 'Hawaii', 'Connecticut', 'California', 'Kansas', 'Utah', 'North Dakota', 'New Mexico', 'Nebraska', 'Pennsylvania', 'Louisiana', 'New Jersey', 'Arizona', 'Colorado', 'Maryland', 'Oregon', 'Missouri', 'Virginia', 'Rhode Island', 'Mississippi', 'South Carolina', 'Illinois', 'Texas', 'Florida', 'Washington', 'District of Columbia', 'Kentucky', 'Minnesota', 'Iowa', 'Alabama', 'New Hampshire', 'Idaho', 'South Dakota', 'Indiana', 'Michigan', 'North Carolina', 'Ohio' ] */ // states['North Carolina'].superiors.includes('Ohio') === true // so why is 'Ohio' listed beneath 'North Carolina'? }); Here is the JSON data in case the data in my link gets vandalized: {"Iowa":{"inferiors":[],"superiors":["Alaska","Oklahoma","California","Hawaii","New Jersey","Virginia","Florida","Washington","Minnesota","Texas","Idaho","Alabama","Ohio"]},"Ohio":{"inferiors":["North Carolina","Michigan","Iowa","New Hampshire"],"superiors":["New York","California","Arizona","Illinois","Texas","Pennsylvania","Florida","Indiana","Tennessee","Massachusetts","Washington","Colorado","District of Columbia","Maryland","Kentucky","Oregon","Oklahoma","Wisconsin","Nevada","New Mexico","Missouri","Virginia","Georgia","Nebraska","Minnesota","Louisiana","Hawaii","Alaska","New Jersey","Idaho","Alabama","Arkansas","Utah","Rhode Island","Mississippi","South Carolina","Connecticut","Montana","Kansas","North Dakota","South Dakota"]},"Utah":{"inferiors":["Idaho","South Dakota","Ohio","Michigan"],"superiors":["New York"]},"Idaho":{"inferiors":["Ohio","Iowa","South Dakota","Michigan","North Carolina"],"superiors":["Alaska","Oklahoma","California","Hawaii","Minnesota","New Jersey","Virginia","Florida","Washington","Texas","New York","Louisiana","Illinois","Arkansas","Utah","Rhode Island","Mississippi","Maryland","Nebraska","District of Columbia","Kentucky","Connecticut"]},"Texas":{"inferiors":["North Carolina","Michigan","Ohio","Indiana","Idaho","Alabama","Iowa"],"superiors":["New York","California","Tennessee","Massachusetts","Oklahoma","Wisconsin","Nevada","New Mexico","Alaska","Hawaii"]},"Alaska":{"inferiors":["California","Hawaii","New Jersey","Virginia","Florida","Washington","Minnesota","Texas","Idaho","Alabama","Ohio","Iowa","New Mexico","Mississippi","Rhode Island","North Dakota","South Carolina","District of Columbia","Colorado","Arizona","Kentucky","New Hampshire","Oregon","Nebraska","Illinois","Indiana","South Dakota","North Carolina"],"superiors":["Tennessee"]},"Hawaii":{"inferiors":["Minnesota","Kentucky","Washington","Pennsylvania","Illinois","Georgia","Maryland","Ohio","New Jersey","Virginia","Florida","Texas","Idaho","Alabama","Iowa","Mississippi","Rhode Island","North Dakota","South Carolina","District of Columbia","Colorado","Arizona","New Hampshire","Missouri","Utah","Louisiana","Michigan"],"superiors":["New York","Tennessee","Oklahoma","Alaska","Nevada"]},"Kansas":{"inferiors":["Indiana","North Carolina"],"superiors":["Wisconsin","New York","California"]},"Nevada":{"inferiors":["California","New Mexico","Illinois","Texas","Missouri","Virginia","District of Columbia","Ohio","North Carolina","Michigan","Maryland","Colorado","Arizona","Oregon","Indiana","Kentucky","Louisiana","Florida","Hawaii","Massachusetts","South Carolina","Mississippi","Minnesota","North Dakota","New Hampshire","Rhode Island","Washington","Utah","New Jersey","Nebraska","Alabama","South Dakota"],"superiors":["Tennessee","Oklahoma","Wisconsin"]},"Oregon":{"inferiors":["Ohio","Indiana","North Carolina","Michigan","Alabama","South Dakota"],"superiors":["New York","Tennessee","Massachusetts","Oklahoma","Wisconsin","California","Nevada","Alaska"]},"Alabama":{"inferiors":["Ohio","Iowa","North Carolina"],"superiors":["Tennessee","Nevada","Alaska","Nebraska","New Mexico","New Jersey","Kentucky","Oregon","Rhode Island","Illinois"]},"Arizona":{"inferiors":["Indiana","Ohio","North Carolina","Michigan","New Hampshire"],"superiors":["California","New York","Tennessee","Massachusetts","Wisconsin","Nevada","New Mexico","Alaska","Hawaii"]},"Florida":{"inferiors":["Indiana","Ohio","North Carolina","Michigan","Iowa","Idaho","South Dakota"],"superiors":["Tennessee","New York","Massachusetts","Wisconsin","California","New Mexico","Oklahoma","Nevada","Alaska","Hawaii"]},"Georgia":{"inferiors":["Ohio"],"superiors":["Tennessee","New York","Oklahoma"]},"Indiana":{"inferiors":["Ohio","North Carolina","Michigan","South Dakota"],"superiors":["New York","California","Arizona","Illinois","Texas","Pennsylvania","Florida","Oklahoma","Tennessee","Wisconsin","Oregon","District of Columbia","Maryland","Virginia","Washington","Missouri","Nebraska","Colorado","Kansas","Kentucky","Nevada","Louisiana","New Mexico","Minnesota","Rhode Island","Connecticut","Mississippi","Alaska","New Jersey"]},"Montana":{"inferiors":["North Carolina"],"superiors":["Massachusetts","Oklahoma","New Mexico"]},"Arkansas":{"inferiors":["South Dakota","Ohio","Michigan"],"superiors":["New York","California"]},"Colorado":{"inferiors":["Ohio","Michigan","North Carolina"],"superiors":["New York","Tennessee","Massachusetts","Wisconsin","California","Nevada"]},"Illinois":{"inferiors":["Indiana","Ohio","Michigan","South Dakota","Alabama","North Carolina"],"superiors":["New York","California","Tennessee","Massachusetts","Oklahoma","Wisconsin","Nevada","New Mexico","Hawaii"]},"Kentucky":{"inferiors":["Ohio","Indiana","Michigan","North Carolina","Idaho","South Dakota","New Hampshire"],"superiors":["New York","Tennessee","Massachusetts","Wisconsin","Nevada","California","Oklahoma","Hawaii","New Mexico","Alaska"]},"Maryland":{"inferiors":["Ohio","North Carolina","Michigan","Indiana","Idaho","South Dakota"],"superiors":["New York","Tennessee","Massachusetts","Oklahoma","California","Wisconsin","Nevada","New Mexico"]},"Michigan":{"inferiors":[],"superiors":["Florida","New York","California","Illinois","Texas","Pennsylvania","Arizona","Tennessee","Oklahoma","Wisconsin","Nevada","New Mexico","District of Columbia","Missouri","Virginia","North Carolina","Ohio","Washington","Georgia","Maryland","Nebraska","Colorado","Indiana","Oregon","Louisiana","Kentucky","Massachusetts","Hawaii","Rhode Island","Mississippi","Utah"]},"Missouri":{"inferiors":["Ohio","North Carolina","Michigan","Indiana"],"superiors":["Tennessee","Oklahoma","Wisconsin","California","Nevada","New Mexico","New York","Massachusetts","Hawaii"]},"Nebraska":{"inferiors":["Ohio","North Carolina","Michigan","Indiana","Idaho","South Dakota","Alabama"],"superiors":["New York","Tennessee","California","New Mexico","Oklahoma","Nevada","Alaska"]},"New York":{"inferiors":["California","Illinois","Texas","Pennsylvania","Arizona","Florida","Indiana","Ohio","North Carolina","Michigan","Washington","Colorado","District of Columbia","Maryland","Kentucky","Oregon","Massachusetts","New Mexico","Minnesota","Missouri","Nebraska","Virginia","Kansas","Louisiana","Georgia","Hawaii","Arkansas","Utah","Rhode Island","Mississippi","Idaho","South Dakota","South Carolina","New Jersey","Connecticut","New Hampshire"],"superiors":["Wisconsin","Tennessee","Oklahoma"]},"Oklahoma":{"inferiors":["Nevada","California","New Mexico","Illinois","Texas","Missouri","Virginia","District of Columbia","Ohio","North Carolina","Michigan","Wisconsin","Oregon","Maryland","Washington","Indiana","New York","Hawaii","Minnesota","Kentucky","Pennsylvania","Georgia","Florida","Louisiana","Idaho","South Dakota","Nebraska","Rhode Island","Connecticut","Mississippi","South Carolina","New Jersey","New Hampshire","Montana","Kansas"],"superiors":["Tennessee"]},"Virginia":{"inferiors":["Ohio","North Carolina","Michigan","Indiana","Iowa","Idaho","South Dakota"],"superiors":["Tennessee","Oklahoma","Wisconsin","California","Nevada","New Mexico","New York","Alaska","Hawaii"]},"Louisiana":{"inferiors":["Indiana","Ohio","Michigan","Idaho","South Dakota"],"superiors":["Nevada","New York","California","Tennessee","New Mexico","Oklahoma"]},"Minnesota":{"inferiors":["Ohio","North Carolina","Idaho","Alabama","Iowa","South Dakota","Michigan","Indiana","New Hampshire"],"superiors":["Wisconsin","New York","California","Massachusetts","New Mexico","Tennessee","Oklahoma","Hawaii","Alaska","Nevada"]},"Tennessee":{"inferiors":["Illinois","Washington","Florida","Colorado","District of Columbia","Texas","Maryland","Kentucky","Oregon","Arizona","Ohio","Oklahoma","Wisconsin","Nevada","California","New Mexico","Missouri","Virginia","North Carolina","Michigan","Georgia","Nebraska","Indiana","Pennsylvania","New York","Hawaii","Minnesota","Louisiana","Rhode Island","Mississippi","Utah","Alaska","New Jersey","Alabama","South Dakota"],"superiors":[]},"Wisconsin":{"inferiors":["Nevada","California","New Mexico","Illinois","Texas","Missouri","Virginia","District of Columbia","Ohio","North Carolina","Michigan","Oregon","Maryland","Washington","Indiana","Massachusetts","Pennsylvania","Florida","Minnesota","New York","Kansas","Arizona","Kentucky","Colorado"],"superiors":["Oklahoma","Tennessee"]},"California":{"inferiors":["Illinois","Texas","Pennsylvania","Arizona","Florida","Indiana","Ohio","North Carolina","Michigan","Missouri","Virginia","District of Columbia","Oregon","Maryland","Washington","Massachusetts","New Mexico","Minnesota","Nebraska","Colorado","Kansas","Kentucky","Louisiana","New Jersey","Idaho","Alabama","Iowa","Arkansas","Utah","Rhode Island","Mississippi","South Dakota","South Carolina","Connecticut","New Hampshire"],"superiors":["New York","Tennessee","Oklahoma","Wisconsin","Nevada","Alaska"]},"New Jersey":{"inferiors":["Iowa"],"superiors":["Alaska","Oklahoma","California","Hawaii","New York","New Mexico","Tennessee","Nevada"]},"New Mexico":{"inferiors":["Illinois","Texas","Missouri","Virginia","District of Columbia","Ohio","North Carolina","Michigan","Pennsylvania","Florida","Minnesota","Indiana","Kentucky","Louisiana","Arizona","Washington","Nebraska","Maryland","South Carolina","New Jersey","Rhode Island","Connecticut","New Hampshire","Mississippi","North Dakota","Colorado","Montana","Kansas","Oregon","Alabama","South Dakota"],"superiors":["Wisconsin","Tennessee","Oklahoma","New York","California","Nevada","Alaska"]},"Washington":{"inferiors":["Ohio","North Carolina","Michigan","Indiana","Iowa"],"superiors":["Tennessee","New York","Massachusetts","California","Oklahoma","Wisconsin","New Mexico","Hawaii","Alaska","Nevada"]},"Connecticut":{"inferiors":["Idaho","Indiana","South Dakota","North Carolina","Ohio","New Hampshire"],"superiors":["New York","Oklahoma","New Mexico","Massachusetts"]},"Mississippi":{"inferiors":["Idaho","South Dakota","Ohio","Michigan","Indiana","North Carolina","New Hampshire"],"superiors":["Alaska","Tennessee","Hawaii","New Mexico","Nevada","Massachusetts"]},"North Dakota":{"inferiors":["Ohio","New Hampshire"],"superiors":["Alaska","Tennessee","Hawaii","New Mexico","Nevada","Massachusetts"]},"Pennsylvania":{"inferiors":["North Carolina","Michigan","Indiana","Ohio","New Hampshire"],"superiors":["New York","California","Wisconsin","New Mexico","Massachusetts","Tennessee","Oklahoma","Hawaii"]},"Rhode Island":{"inferiors":["Idaho","South Dakota","Ohio","Michigan","Indiana","North Carolina","New Hampshire","Alabama"],"superiors":["New York","Oklahoma","New Mexico","California","Alaska","Tennessee","Hawaii","Nevada","Massachusetts"]},"South Dakota":{"inferiors":["Ohio","North Carolina"],"superiors":["New York","California","Illinois","Arkansas","Louisiana","Minnesota","Utah","Rhode Island","Florida","Mississippi","Maryland","Idaho","Oklahoma","Nebraska","District of Columbia","Kentucky","Connecticut","Virginia","Indiana"]},"Massachusetts":{"inferiors":["Illinois","Washington","Florida","Colorado","District of Columbia","Texas","Maryland","Kentucky","Oregon","Arizona","Ohio","Pennsylvania","Minnesota","Indiana","North Carolina","Montana","Connecticut","Rhode Island","Kansas","South Carolina","Mississippi","North Dakota","New Hampshire","Missouri","Utah","Louisiana","Michigan"],"superiors":["Wisconsin","New York","California","Nevada","Tennessee"]},"New Hampshire":{"inferiors":[],"superiors":["Oklahoma","New York","New Mexico","California","Pennsylvania","Maryland","South Carolina","Virginia","New Jersey","Rhode Island","Connecticut","Alaska","Nevada","Hawaii","Massachusetts","Mississippi","Minnesota","Arizona","North Dakota","Kentucky","Ohio"]},"North Carolina":{"inferiors":["Michigan"],"superiors":["New York","California","Texas","Illinois","Pennsylvania","Arizona","Florida","Indiana","Ohio","Wisconsin","Tennessee","Oklahoma","New Mexico","Nevada","Washington","Georgia","District of Columbia","Missouri","Maryland","Nebraska","Massachusetts","Minnesota","Colorado","Oregon","Virginia","Kentucky","Rhode Island","Connecticut","Mississippi","Idaho","Montana","Kansas","Alaska","New Jersey","Alabama","South Dakota"]},"South Carolina":{"inferiors":["New Hampshire"],"superiors":["Oklahoma","New York","New Mexico","California","Alaska","Tennessee","Hawaii","Nevada","Massachusetts"]},"District of Columbia":{"inferiors":["Ohio","North Carolina","Michigan","Indiana","Idaho","South Dakota"],"superiors":["New York","Tennessee","Massachusetts","Wisconsin","Oklahoma","California","Nevada","New Mexico","Alaska","Hawaii"]}}
You have a partial order only not a total order (not all states list all others in their superiors/inferiors list), so your score calculation doesn't work. States end up with a score depending on how often they were mentioned, not what their relative order is. You'll need to implement a topological sort algorithm.
Your data doesn't contain contradictions, but it certainly doesn't list everything correctly. Example: Iowa-Oklahoma pair. Oklahoma is listed as being superior to Iowa, but Iowa is not listed as being inferior to Oklahoma.
Typehead.js dropdown does not appear
I have been trying to get typehead.js library to work on a dropdown list that pulls from a mysql database for a while but it has not worked. I decided to try the basics first and tried to populate the dropdown from a simple array instead of a database as shown in the typehead.js docs examples. I created this codepen but I havent been able to get the dropdown working over there as well. I copied the typehead.js lib to the JS section of codepen. Here is my HTML: <!DOCTYPE html> <html lang="en"> <head> <title>Typehead</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="http://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <style> .typeahead { z-index: 1051; } </style> </head> <body> <div id="the-basics"> <input class="typeahead" type="text" placeholder="States of USA"> </div> <script> var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push(str); } }); cb(matches); }; }; var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', source: substringMatcher(states) }); </script> </body> The drop down list does not appear at all.
Seems the copy paste script might have been broken in your case. Just import it from a CDN like this <script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"> </script> Checkout this codepen
how to show "no match found" in typehead in angular ui?
What I want to do is this: when a user starts typing in the typehead input and no matches are found it should show a message saying "no match found". Below is the code and a plunker: HTML <html ng-app="ui.bootstrap.demo"> <head> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.js"></script> <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.0.2.js"></script> <script src="example.js"></script> <link href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <script type="text/ng-template" id="customTemplate.html"> <a> <img ng-src="http://upload.wikimedia.org/wikipedia/commons/thumb/{{match.model.flag}}" width="16"> <span ng-bind-html="match.label | uibTypeaheadHighlight:query"></span> </a> </script> <div class='container-fluid typeahead-demo' ng-controller="TypeaheadCtrl"> <h4>Custom templates for results</h4> <pre>Model: {{customSelected | json}}</pre> <input type="text" ng-model="customSelected" placeholder="Custom template" uib-typeahead="state as state.name for state in statesWithFlags | filter:{name:$viewValue}" typeahead-template-url="customTemplate.html" class="form-control" typeahead-show-hint="true" typeahead-min-length="0"> </div> </body> </html> JavaScript angular.module('ui.bootstrap.demo', ['ngAnimate', 'ui.bootstrap']); angular.module('ui.bootstrap.demo').controller('TypeaheadCtrl', function($scope, $http) { var _selected; $scope.selected = undefined; $scope.states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Dakota', 'North Carolina', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming']; // Any function returning a promise object can be used to load values asynchronously $scope.getLocation = function(val) { return $http.get('//maps.googleapis.com/maps/api/geocode/json', { params: { address: val, sensor: false } }).then(function(response){ return response.data.results.map(function(item){ return item.formatted_address; }); }); }; $scope.ngModelOptionsSelected = function(value) { if (arguments.length) { _selected = value; } else { return _selected; } }; $scope.modelOptions = { debounce: { default: 500, blur: 250 }, getterSetter: true }; $scope.statesWithFlags = [{'name':'Alabama','flag':'5/5c/Flag_of_Alabama.svg/45px-Flag_of_Alabama.svg.png'},{'name':'Alaska','flag':'e/e6/Flag_of_Alaska.svg/43px-Flag_of_Alaska.svg.png'},{'name':'Arizona','flag':'9/9d/Flag_of_Arizona.svg/45px-Flag_of_Arizona.svg.png'},{'name':'Arkansas','flag':'9/9d/Flag_of_Arkansas.svg/45px-Flag_of_Arkansas.svg.png'},{'name':'California','flag':'0/01/Flag_of_California.svg/45px-Flag_of_California.svg.png'},{'name':'Colorado','flag':'4/46/Flag_of_Colorado.svg/45px-Flag_of_Colorado.svg.png'},{'name':'Connecticut','flag':'9/96/Flag_of_Connecticut.svg/39px-Flag_of_Connecticut.svg.png'},{'name':'Delaware','flag':'c/c6/Flag_of_Delaware.svg/45px-Flag_of_Delaware.svg.png'},{'name':'Florida','flag':'f/f7/Flag_of_Florida.svg/45px-Flag_of_Florida.svg.png'},{'name':'Georgia','flag':'5/54/Flag_of_Georgia_%28U.S._state%29.svg/46px-Flag_of_Georgia_%28U.S._state%29.svg.png'},{'name':'Hawaii','flag':'e/ef/Flag_of_Hawaii.svg/46px-Flag_of_Hawaii.svg.png'},{'name':'Idaho','flag':'a/a4/Flag_of_Idaho.svg/38px-Flag_of_Idaho.svg.png'},{'name':'Illinois','flag':'0/01/Flag_of_Illinois.svg/46px-Flag_of_Illinois.svg.png'},{'name':'Indiana','flag':'a/ac/Flag_of_Indiana.svg/45px-Flag_of_Indiana.svg.png'},{'name':'Iowa','flag':'a/aa/Flag_of_Iowa.svg/44px-Flag_of_Iowa.svg.png'},{'name':'Kansas','flag':'d/da/Flag_of_Kansas.svg/46px-Flag_of_Kansas.svg.png'},{'name':'Kentucky','flag':'8/8d/Flag_of_Kentucky.svg/46px-Flag_of_Kentucky.svg.png'},{'name':'Louisiana','flag':'e/e0/Flag_of_Louisiana.svg/46px-Flag_of_Louisiana.svg.png'},{'name':'Maine','flag':'3/35/Flag_of_Maine.svg/45px-Flag_of_Maine.svg.png'},{'name':'Maryland','flag':'a/a0/Flag_of_Maryland.svg/45px-Flag_of_Maryland.svg.png'},{'name':'Massachusetts','flag':'f/f2/Flag_of_Massachusetts.svg/46px-Flag_of_Massachusetts.svg.png'},{'name':'Michigan','flag':'b/b5/Flag_of_Michigan.svg/45px-Flag_of_Michigan.svg.png'},{'name':'Minnesota','flag':'b/b9/Flag_of_Minnesota.svg/46px-Flag_of_Minnesota.svg.png'},{'name':'Mississippi','flag':'4/42/Flag_of_Mississippi.svg/45px-Flag_of_Mississippi.svg.png'},{'name':'Missouri','flag':'5/5a/Flag_of_Missouri.svg/46px-Flag_of_Missouri.svg.png'},{'name':'Montana','flag':'c/cb/Flag_of_Montana.svg/45px-Flag_of_Montana.svg.png'},{'name':'Nebraska','flag':'4/4d/Flag_of_Nebraska.svg/46px-Flag_of_Nebraska.svg.png'},{'name':'Nevada','flag':'f/f1/Flag_of_Nevada.svg/45px-Flag_of_Nevada.svg.png'},{'name':'New Hampshire','flag':'2/28/Flag_of_New_Hampshire.svg/45px-Flag_of_New_Hampshire.svg.png'},{'name':'New Jersey','flag':'9/92/Flag_of_New_Jersey.svg/45px-Flag_of_New_Jersey.svg.png'},{'name':'New Mexico','flag':'c/c3/Flag_of_New_Mexico.svg/45px-Flag_of_New_Mexico.svg.png'},{'name':'New York','flag':'1/1a/Flag_of_New_York.svg/46px-Flag_of_New_York.svg.png'},{'name':'North Carolina','flag':'b/bb/Flag_of_North_Carolina.svg/45px-Flag_of_North_Carolina.svg.png'},{'name':'North Dakota','flag':'e/ee/Flag_of_North_Dakota.svg/38px-Flag_of_North_Dakota.svg.png'},{'name':'Ohio','flag':'4/4c/Flag_of_Ohio.svg/46px-Flag_of_Ohio.svg.png'},{'name':'Oklahoma','flag':'6/6e/Flag_of_Oklahoma.svg/45px-Flag_of_Oklahoma.svg.png'},{'name':'Oregon','flag':'b/b9/Flag_of_Oregon.svg/46px-Flag_of_Oregon.svg.png'},{'name':'Pennsylvania','flag':'f/f7/Flag_of_Pennsylvania.svg/45px-Flag_of_Pennsylvania.svg.png'},{'name':'Rhode Island','flag':'f/f3/Flag_of_Rhode_Island.svg/32px-Flag_of_Rhode_Island.svg.png'},{'name':'South Carolina','flag':'6/69/Flag_of_South_Carolina.svg/45px-Flag_of_South_Carolina.svg.png'},{'name':'South Dakota','flag':'1/1a/Flag_of_South_Dakota.svg/46px-Flag_of_South_Dakota.svg.png'},{'name':'Tennessee','flag':'9/9e/Flag_of_Tennessee.svg/46px-Flag_of_Tennessee.svg.png'},{'name':'Texas','flag':'f/f7/Flag_of_Texas.svg/45px-Flag_of_Texas.svg.png'},{'name':'Utah','flag':'f/f6/Flag_of_Utah.svg/45px-Flag_of_Utah.svg.png'},{'name':'Vermont','flag':'4/49/Flag_of_Vermont.svg/46px-Flag_of_Vermont.svg.png'},{'name':'Virginia','flag':'4/47/Flag_of_Virginia.svg/44px-Flag_of_Virginia.svg.png'},{'name':'Washington','flag':'5/54/Flag_of_Washington.svg/46px-Flag_of_Washington.svg.png'},{'name':'West Virginia','flag':'2/22/Flag_of_West_Virginia.svg/46px-Flag_of_West_Virginia.svg.png'},{'name':'Wisconsin','flag':'2/22/Flag_of_Wisconsin.svg/45px-Flag_of_Wisconsin.svg.png'},{'name':'Wyoming','flag':'b/bc/Flag_of_Wyoming.svg/43px-Flag_of_Wyoming.svg.png'}]; }); Here is the demo in plunker.
Use typeahead-no-results. Add the following to your input typeahead-no-results="noResults" Then add the following, or similar, below. <div ng-show="noResults"> <i class="glyphicon glyphicon-remove"></i> No Match Found </div> I've amended your Plunkr here
Why is typeahead matching periods?
I am using the same code from the typeahead example here. However if you type in a period . the dropdown will appear with matches. Is all this code above the array definition necessary? Is there an easier way to accomplish the same thing where you won't get matches for periods if there are no periods in your array? I see the bloodhound example below it accomplishes the same thing and doesn't match periods but is it using var states to define an array and then using var states to construct a new bloodhound engine is this a mistake? Copied code from the website: var substringMatcher = function(strs) { return function findMatches(q, cb) { var matches, substringRegex; // an array that will be populated with substring matches matches = []; // regex used to determine if a string contains the substring `q` substrRegex = new RegExp(q, 'i'); // iterate through the pool of strings and for any string that // contains the substring `q`, add it to the `matches` array $.each(strs, function(i, str) { if (substrRegex.test(str)) { matches.push(str); } }); cb(matches); }; }; var states = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming' ]; $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 1 }, { name: 'states', source: substringMatcher(states) }); In my case I am generating an array of tags so instead of the states I am using var tags = <%= raw Tag.all.pluck(:name) %>;
You may find indexOf to be more useful than a regex for your application. if (haystack.indexOf(needle) != -1) { /* needle is in haystack */ } or, case insensitively: if (haystack.toLowerCase().indexOf(needle.toLowerCase()) != -1) { } something like this: function findMatches(q, cb) { var lq = q.toLowerCase(); var matches = []; $.each(strs, function(i, str) { if (str.toLowerCase().indexOf(lq) != -1) matches.push(str); }); cb(matches); }
So regular expressions are "complicated", and easy to get wrong. "." for instance has special meaning in regex which matches any charachter except newline in JS, so for example based on Mozilla's docs RexExp(".n", "i") would match ".n", "an", "in", "?n" and many more. Regular expressions are difficult to get right. #John-Hascall's suggestion is a good fix for the problem.