如何从 ng-repeat 中获取选定的值

How to get selected value from ng-repeat

这是我的代码。

我正在通过 ng-repeat 获取数据并将其显示在下面的代码中。

我想要的是,如果我单击其中一个名称,它应该会用该名称提醒我。我怎样才能做到这一点?

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

myfriend.controller('myfriendController', function($scope) 
{
   $scope.record = [
       {     "id" : "01",
            "firstname" : "Mohan ",
            "middlename" : "K",
            "lastname" : "Futterkiste1"
        },{
             "id" : "04",
            "firstname" : "Rohan ",
            "middlename" : "A",
            "lastname" : "Futterkiste2"
        },{
              "id" : "08",
            "firstname" : "sohan ",
            "middlename" : "M",
            "lastname" : "Futterkiste3"
        }
   ]
               
    
});
<html>
  <head>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>

  </head>
  <body ng-app="myfriend">
    
    
    
    <table class="table" style="border:1px red solid; width:100%; "  ng-controller="myfriendController">
      <thead>
        <tr>
         <th>Id</th>
          <th>First name</th>
          <th>Middle name</th>
             <th>Last name</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="x in record">
             <th>{{x.id}}</th>
             <th ng-click="selectInfo(x.id)">    {{x.firstname}}</th>
                <th>{{x.middlename}}</th>
                <th>{{x.lastname}}</th>
        </tr>
      </tbody>  
 </table> 
  <body>
</html>
 

你到目前为止进展顺利。您添加了 ng-click 事件。但是你需要做的是在控制器中获取名称,你需要将当前项目作为参数传递 看这里 <th ng-click="selectInfo(x)">{{x.firstname}}</th>

并在控制器中 做一个函数

$scope.selectInfo = function (item) {
   alert(item.firstname);
   // Or use this to do whatever you want
}

您需要修改 html 并在控制器文件中添加 selectInfo 函数。

html

<table>
      <tr ng-repeat="x in record">
                    <th>{{x.id}}</th>
                    <th ng-click="selectInfo(x.firstname)">    {{x.firstname}}</th>
                    <th ng-click="selectInfo(x.middlename)">{{x.middlename}}</th>
                    <th ng-click="selectInfo(x.lastname)">{{x.lastname}}</th>
                  </tr>
    </table>

代码

$scope.selectInfo=function(name){
alert(name);
}