Skip to content
Advertisement

Angular create element if another is non-existent

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

JavaScript

States

JavaScript

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.

Advertisement

Answer

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:

JavaScript

js:

JavaScript

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
Advertisement