按钮上的不同警报单击

时间:2017-09-19 05:14:38

标签: javascript html angularjs

我的任务是使用ng-repeat显示一个表格,例如:1234567,每行都有一个按钮。单击该按钮,我想显示带有相应编号的警报。

以下是我的HTML文件。

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="myApp.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">

    <table>
    <tr ng-repeat="x in records">

        <td>{{x.Digit}}</td>

       <td><input type="button" value="Press Me" ng-click="test(record)" /></td> 
    </tr>
</table>            

</body> 

</html>
<html>

<body>

JS档案。

var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
  // $scope.records = [1,2,3,4,5,6,7];
    $scope.records = [
    {
      "Digit" : "1",
    },

    {
      "Digit" : "2",
    },
    {
      "Digit" : "3",
    },
    {
      "Digit" : "4",
    },
    {
      "Digit" : "5",
    },
    {
      "Digit" : "6",
    },
    {
      "Digit" : "7",
    }
  ]
  $scope.test = function(text) {
    alert("You clicked");
    // alert(text);
  }
// }).directive('li',function(){
//   return {
//        template: '<records> <record  ng-click="test(record)" ng-repeat="record in records"> {{ record }}   </record></br></records> '
//   }     
// });

// app.controller("myCtrl", function($scope) {

// $scope.myFunction = function(text){
//       alert(text);
//     };
});

2 个答案:

答案 0 :(得分:1)

您需要传递 x 而不是 record

<tr ng-repeat="x in records">
        <td>{{x.Digit}}</td>
       <td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td> 
</tr>

<强>样本

&#13;
&#13;
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
  // $scope.records = [1,2,3,4,5,6,7];
    $scope.records = [
    {
      "Digit" : "1",
    },

    {
      "Digit" : "2",
    },
    {
      "Digit" : "3",
    },
    {
      "Digit" : "4",
    },
    {
      "Digit" : "5",
    },
    {
      "Digit" : "6",
    },
    {
      "Digit" : "7",
    }
  ]
  $scope.test = function(text) {
    alert("You clicked "+ text);   
  }

});
&#13;
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
    <table>
    <tr ng-repeat="x in records">
        <td>{{x.Digit}}</td>
       <td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td> 
    </tr>
</table>       

</body> 

</html>
<html>

<body>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于你的迭代器是x,所以传递x.digit,而不是记录。

<tr ng-repeat="x in records">
        <td>{{x.Digit}}</td>
       <td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td> 
</tr>