Tuesday, March 8, 2016

Angular Recipe: Avoid empty option in HTML select element

HTML select in Angular JS


HTML select element is often used to create a drop-down list.
You could use either ng-repeat or ng-options directive to fulfill it with options.
Note that the value of a select directive used without ngOptions is always a string.
That's why i prefer to use ng-options directive rather than ng-repeat one.
Note: if ng-model value is undefined, has a wrong type or is not contained among the options set, than selected element into your drop-down would be empty.
Note: It also might happen when ng-model variable is distinct into the child-scope from the one that u've defined in JS.
If you are working with objects that have an identifier property, you should track by the identifier instead of the whole object.

Should you reload your data later, ngRepeat will not have to rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones. For large collections, this significantly improves rendering performance. If you don't have a unique identifier, track by $index can also provide a performance boost.
According to (Prototypical inheritance) your directive might create a child-scope, which could distinct your ng-model="fooBar" variable and no longer refer up to the parent’s $scope.fooBar variable.

To not storing the data directly on the scope helps in this case.

6 comments:

  1. Thank you for your very helpful post! Help me through the select being blank issue that I struggled with for quite sometime. Keep it up!

    ReplyDelete
  2. I really like and appreciate your post. Really thank you! Fantastic.
    python training
    angular js training
    selenium trainings

    ReplyDelete
  3. Great post.I'm glad to see people are still interested of Article.Thank you for an interesting read........
    Offshore Angularjs 2 Developer in India

    ReplyDelete
  4. Great blog the content is informative and engaging. Visit my website to get best Information
    Frozen Shoulder Treatment in Surrey

    ReplyDelete
  5. Wonderful blog with great piece of information. Visit my website to get best Information
    vintage oval mirror

    ReplyDelete