Angular JS Magazine

joi, 4 septembrie 2014

Using Select Elements (ng-options)

In tip Angular and Form Elements - part 1 you saw that when a new player was added in the table, you can specify only his name, but not the rank. Since the rank is a number, we can provide a HTML select list for it. The below code allows us to provide players between [6,10] ranks using ng-options attribute. This attribute can be used to generate option elements from arrays and objects:

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../angular/angular.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                    $scope.addNewPlayer = function (newPlayer) {
                        if (angular.isDefined(newPlayer)) {
                            $scope.atp.push({name:, rank: newPlayer.ranking});
                            var index = $scope.ranks.indexOf(newPlayer.ranking);
                            $scope.ranks.splice(index, 1);
                            if($scope.ranks.length > 0) {
                                $scope.player.ranking = $scope.ranks[0];
<div ng-app="atpModule" ng-controller="atpCtrl" ng-init="atp=[
     { name: 'Nadal, Rafael (ESP)', rank: 1 },
     { name: 'Djokovic, Novak (SRB)', rank: 2 },
     { name: 'Federer, Roger (SUI)', rank: 3 },
     { name: 'Wawrinka, Stan (SUI)', rank: 4 },
     { name: 'Ferrer, David (ESP)', rank: 5 }]; ranks=[6,7,8,9,10]; player.ranking=6;">

    <div id="atpPanel" class="panel">
        <h3 class="panel-header">ATP SINGLES RANKINGS</h3>
        <table class="table">
            <tr ng-repeat="item in atp">
    <div class="col-xs-6">
        <div class="well">
            <div class="form-group row">
                <label for="playerNameId">Player Name:</label>
                <input id="playerNameId" class="form-control" ng-model="">
            <div class="form-group row">
                <label for="playerRankId">Player Rank:</label>
                <select id="playerRankId" ng-model="player.ranking" 
                             ng-options="item for item in ranks">
            <button class="btn btn-primary btn-block"
                         ng-disabled="ranks.length == 0" ng-click="addNewPlayer(player)">
                Add Player