简体   繁体   中英

How can I pass a parameter to ng-click inside an ng-repeat?

I have this code in which I am repeating over an array and want to add a functionality that if I click on a row, its data is displayed somewhere else on the same page.

<table>
  <button ng-click="console.log('hello')">view</td>
  <div>
    <tr ng-repeat="contact in contacts | filter:searchText" >
      <td>{{contact.city}}
      </td>
      <td>{{contact.firstName}}</td>
      <td><button ng-click="console.log(contact.id)">view</td>
    </tr>
  </div>
  </table>

I can't seem to figure out why none of the ng-click's are working even when I write it to output a simple message to the console.

When you call console.log() from ng-click , it is actually looking for $scope.console.log() , which does not exist. You need to create a function in your controller that takes an input, and then calls the javascript console.log() function.

$scope.log = function(value){
  console.log(value);
}

Then you bind to it like this:

<button ng-click="log(contact.id)">

Demo

Yes, @Jerrad is right. But if you want to print the whole row data you have to pass the whole contact object into the function. And your HTML is also not correct.

Working code is here.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
</head>

<body ng-app>
    <table ng-controller="controller">
        <input type="text" ng-model="searchText" />
        <div>
            <tr ng-repeat="contact in contacts | filter:searchText">
                <td>{{contact.city}}
                </td>
                <td>{{contact.firstName}}</td>
                <td>
                    <button ng-click="getRowData(contact)">view</button>
            </tr>
        </div>
    </table>
    <script>
        function controller($scope, $http) {
            $scope.contacts = [
                {'city':'City 1', 'firstName':'Firstname 1'},
                {'city':'City 2', 'firstName':'Firstname 2'},
            ];

            $scope.getRowData = function(data) {
                console.log(data.city+'==='+data.firstName);
            }
        }
    </script>
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM