AngularJS - SPLessons

AngularJS Select

Chapter 17

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

AngularJS Select

AngularJS Select

shape Description

AngularJS Select allows to create dropdown boxes depending on array items, or object items with the help of ng-options. But before, it is better to know about AngularJS Select using ng-repeat.

ng-repeat

shape Description

The ng-repeat directive repeats the specific HTML elements a given number of times which is the basic directive to create dropdown. A HTML set repeats once per item in a collection which is an array or an object.

shape Syntax

<element ng-repeat=”expression”></element>

shape Example

<html ng-app="app">
  <body>
    <div ng-controller="Test">
      <p>selected item is : {{selectedItem}}</p>
      <select ng-model="selectedItem">
        <option ng-repeat="item in items" value="{{item}}">{{item}}</option>
      </select>
    </div>
  </body>
</html> 


AngularJS code:

var app = angular.module('app',[]);
app.controller('Test',function($scope){
   $scope.items = ['one','two','three','four']
});

The above code doesn’t change when array items has only strings. But, it should be not used when array items has objects. In this case, ng-options is used instead of ng-repeat because element option can hold only string type as its value.So, the above code is written using ng-options like below.

$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];

And the new HTML code looks like below:

<html ng-app="app">
  <body>
    <div ng-controller="Test">
      <p>selected item is : {{selectedItem}}</p>
      <p> age of selected item is : {{selectedItem.age}} </p>
      <select ng-model="selectedItem" ng-options="item.name for item in items">
      </select>
    </div>
  </body>
</html>

In the above example, the initial element of dropdown is empty as “selectedItem” will not have any default value and is undefined. Since there’s no option is selected by default, AngularJS creates a new option tag and select it as default. To fix the issue, just set the “selectedItem” to the first object in the items array.

$scope.selectedItem = $scope.items[0];

Summary

shape Key Points

  • ng-options is mainly designed to fill a dropdown list with options, but ng-repeat has to create options only after the array repeats.
  • ng-options dropdowns allows value selected as the object, but ng-repeat dropdowns must have strings.