Aravi S
Aravi S

Reputation: 109

Getting ngModel value in controller - AngularJS?

The player's name is alerted once submitPlayer is clicked, and I want the corresponding player id too.

HTML

<div class="row">
   <div class="input-field col s12">
     <input id="search" class="search nomargin" type="text" class="validate dark" ng-model="player">
     <label for="search"><i class="fa fa-search" aria-hidden="true"></i> Search Player</label>
   </div>
 </div>

     <div class="searchresultsbox z-depth-1">
       <div class="row nopad nomargin">
     <div class="col s12 nopad nomargin">
           <ul ng-repeat="eachPlayer in player |filter:search">
             <li>{{eachPlayer.name}}</li>
           </ul>
        </div>
       </div>
     </div>

<div class="modalbuttongroup">
    <a href="" class="center waves-effect waves-light btn addplayer" ng-click="submitPlayer()">ADD PLAYER</a>
</div>

Module and Controller

var app = angular.module('playerapp', []);

app.controller("myController", function ($scope) {

    $scope.player=

    [
         {
          "id": "57f2ade2d9913939d0de4af8",
          "name": "A Team Player"

         },
         {
          "id": "57f3d03fd99139333880a2f8",
          "name": "B Team Player"
         },
         {
          "id": "57f3d05ad99139333880a2fa",
          "name": "C Team Player"
         },
         {
          "id": "57f3fff6d991394b3daa2d49",
          "name": "D Team Player"
         },
         {
          "id": "57f422d6d991390ea392762e",
          "name": "E Team Player"
         }
    ]

    $scope.submitPlayer = function() {
        alert(JSON.stringify($scope.player,null,5))
    };
});

Also, I want the player name to be displayed in the textfield once the player is selected and and when clicking 'add player' I want the player ID to be alerted.

Upvotes: 0

Views: 876

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222522

There are few issues with your code,

(i) You are using player as a search value which is a collection, so it should be changed.

  <input id="search" class="search nomargin" type="text" class="validate dark" ng-model="player.name">

and used as a filter,

<ul ng-repeat="eachPlayer in player |filter:player.name">

And there is no way to select player with your html code, so i have added a radio input button to select player and assign to a scope variable.

  <input type="radio" ng-model="selected" name="rdbRisk" ng-change="Assign(selected)" ng-value="eachPlayer" /> {{eachPlayer.name}}

DEMO

Upvotes: 1

Related Questions