【问题标题】:Angular ng-repeat dynamic角度 ng-repeat 动态
【发布时间】:2017-08-22 02:35:35
【问题描述】:

看到这个plunker

在 jQuery 中,我可以获取其 td 的文本并将其置于警报中,但如何在 Angular 中实现呢?我应该将其设为原生 javascript 吗?

这是脚本

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

app.controller('ctrl',function($scope){
  $scope.edit = function(){
    alert("ID = " + $scope.id + "\n NAME = " + $scope.name);
  };
  $scope.items = [
    {id:"1",name:"name 1"},
    {id:"2",name:"name 2"},
    {id:"3",name:"name 3"}
   ];
});

HTML

  <body ng-controller="ctrl" ng-app="plunker">
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>name</th>
          <th>edit</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="x in items">
          <td ng-model="x.id">{{x.id}}</td>
          <td>{{x.name}}</td>
          <td><button ng-click="edit()">edit</button></td>
        </tr>
      </tbody>
    </table>
  </body>

附言

ng-repeat 是动态的,我怎样才能获得它的价值?

【问题讨论】:

  • 为什么不edit(x.id)edit(x)

标签: javascript angularjs


【解决方案1】:

只需将值作为参数传递给编辑函数,

 <td><button ng-click="edit(x)">edit</button></td>

然后函数就是,

$scope.edit = function(x){
  console.log("Id is",x.id);
}

演示

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

app.controller('ctrl',function($scope){
  $scope.edit = function(){
    alert("ID = " + $scope.id + "\n NAME = " + $scope.name);
  };
  $scope.items = [
    {id:"1",name:"name 1"},
    {id:"2",name:"name 2"},
    {id:"3",name:"name 3"}
   ];
   
  $scope.edit = function(x){
   console.log("$$Id is",x.id);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-controller="ctrl" ng-app="plunker">
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>name</th>
          <th>edit</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="x in items">
          <td ng-model="x.id">{{x.id}}</td>
          <td>{{x.name}}</td>
          <td><button ng-click="edit(x)">edit</button></td>
        </tr>
      </tbody>
    </table>
  </body>

【讨论】:

    【解决方案2】:

    让你的函数edit() 接受一个变量,然后将其传入:

    $scope.edit = function(obj){
      alert("ID = " + obj.id + "\n NAME = " + obj.name);
    };
    

    然后:

    <td><button ng-click="edit(x)">edit</button></td>
    

    【讨论】:

      【解决方案3】:

      您可以在控制器中创建一个大小为 items.length 的数组 $scope.itemModel,并使用 $scope.itemModel[$index] 上的 $index 在标记中设置模型,然后通过将 $index 传递给处理程序来访问该项目来自您的控制器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-23
        • 2015-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多