-->

How to get selected value from ng-repeat

2020-03-08 06:07发布

问题:

This is my code.

I m getting data through ng-repeat and showing it as shown in below code.

What I want is if I click on either of the name then it should alert me with that name. How can I achieve this??

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>
 

回答1:

You need to modify html and add selectInfo function in controller file.

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>

code

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


回答2:

You are going good so far. You added the ng-click event. But aal you need to do to get the name in controller is, you need to paas the current item as arguement See Here <th ng-click="selectInfo(x)">{{x.firstname}}</th>

and in the controller make a function

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