在控制器中获取ngModel值 - AngularJS?

时间:2016-10-08 12:44:39

标签: javascript html angularjs angularjs-scope angular-controller

点击submitPlayer后会提醒玩家的名字,我也想要相应的玩家ID。

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>

模块和控制器

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))
    };
});

此外,我希望一旦选择了播放器,并且在点击“添加播放器”时,播放器名称将显示在文本字段中。我希望提醒玩家ID。

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题,

(i)您正在使用播放器作为搜索值,这是一个集合,因此应该更改。

/api

并用作过滤器,

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

并且没有办法用你的html代码选择播放器,所以我添加了一个无线电输入按钮来选择播放器并分配到一个范围变量。

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

<强> DEMO