Angular JS Magazine

sâmbătă, 30 august 2014

Angular and Form Elements - part 1

Let's suppose that we have a table with two columns. In the first column we have the players names and in the second one their ranks. Now, we write a simple form to add new player in this table (the rank is auto-generated):

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="../angular/angular.min.js"></script>
    <link href="../bootstrap/css/bootstrap.css" rel="stylesheet"/>
    <link href="../bootstrap/css/bootstrap-theme.css" rel="stylesheet"/>
     <script>
        angular.module("atpModule", [])
                .controller("atpCtrl", function ($scope) {
                    $scope.addNewPlayer = function (newPlayer) {
                        if (angular.isDefined(newPlayer)){
                            $scope.atp.push({name: newPlayer.name, rank: $scope.atp.length + 1});
                        }
                    };
                });
    </script>
</head>
<body>
<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 }]">

    <div id="atpPanel" class="panel">
        <h3 class="panel-header">ATP SINGLES RANKINGS</h3>
        <table class="table">
            <thead>
            <tr>
                <th>Name</th>
                <th>Rank</th>
            </tr>
            </thead>
            <tbody>
            <tr ng-repeat="item in atp">
                <td>{{item.name}}</td>
                <td>{{item.rank}}</td>
            </tr>
            </tbody>
        </table>
    </div>
    <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="player.name">
            </div>
            <div class="form-group row">
                <label for="playerRankId">Player Rank:</label>
                <span id="playerRankId">{{atp.length + 1}}</span>
            </div>
            <button class="btn btn-primary btn-block" ng-click="addNewPlayer(player)">
                Add Player
            </button>
        </div>
    </div>
</div>
</body>
</html>

Before adding player:

After a player was added (Berdych, Tomas (CZE)):

Niciun comentariu:

Trimiteți un comentariu