如何根据 angularjs 数组中的 属性 对象更新 HTML table

How to update an HTML table based on a property of object in an array in angularjs

我是 angularjs 的新手,尤其是 MEANSTACK。 我有 2 个 HTML table,一个我们命名为 table_1 包含一列多行,每一行包含一些值,我们将其命名为 "prop"。第二个名为 table_2 的 table 包含一些与 table_1 有关的信息。 根据我的研究,我在 table 的一行中也有一个 searching/filtering 的输入标签。 输入标签:

 <div class="input-group search-bar" style="margin-left:5px;">
        <input type="text" ng-model="search" class="searchbar" placeholder="Enter to Search" autofocus>
 </div>

Table_1:

<tbody>
  <tr ng-repeat="obj in objecList | filter:search" ng-click= updateTable_2($index)"> 
    <td>{{obj.prop}}</td>
  </tr>
</tbody>

Table_2:

<tbody>
  <tr ng-repeat="data in datas" >
    <td class="col-xs-4">{{data.data1}}</td>
    <td class="col-xs-4">{{data.data2}}</td>
    <td class="col-xs-4">{{data.data3}}</td>  
  </tr>
</tbody>

我的控制器看起来像这样:

(function(){   
  angular.module('myapp')
   .controller('MyController', MyController)

     function MyController($state,$http,$scope){
       $http.get('api/displayDatas/'+$scope.myList[0].prop)
        .success(function(response){
          $scope.datas = response;
        });

    $scope.updateTable_2 = function(index){
      $scope.myList[0] = list[index];

      $http.get('api/displayDatas/'+$scope.myList[0].prop)
        .success(function(response){
          $scope.datas = response;
        });
    } 
 }   

我的数据模型如下所示:

[
  {"data1":"value1","data2":"value2","prop":"value3"},
  {"data1":"value12","data2":"value22","prop":"value32"},
  {"data1":"value13","data2":"value23","prop":"value33"}
]

我想做的是在 table_1 中搜索特定行时,我希望 table_2 更新关于我在 table_1 中选择的行的值. 但是现在,如果我过滤 table_1 的一行,table_2 的更新是由我发送到我的函数 updateTable_2 的索引完成的,这样它显示的数据与 a 相同之前的位置一样。 我不知道如何以更好的方式更新 table_2。 希望你能明白我的意思。

您的问题不清楚,为 table 2 获取数据的控制器逻辑重复。

如果您正在努力以更简洁的方式将参数传递给您的函数,这里有一个方法。

Pass the object instead of $index to the function from mark-up.

它将具有以下优势

  • 独立于任何带有 $index
  • ng-repeat 警告
  • 松耦合函数,较少依赖全局(如objectList
  • 提高代码的可读性

注意: 传递整个对象而不是 $index 不会损害性能,因为它只是对现有对象的引用。相反,如果你传递 $index,它将作为值传递,因此新内存被分配给函数本地(尽管不相关的性能问题)。

这里是修改后的逻辑。在 Plunker

上查看

  function MyController($http, $scope) {
    $scope.objectList = [{
      "prop": "value3"
    }, {
      "prop": "value32"
    }, {
      "prop": "value33"
    }];

    $scope.updateTable_2 = function(obj) {
      $scope.activeObj = obj;
      $http.get('data.json') //use obj to pass additional param
        .success(function(response) {
          $scope.datas = response;
        });
    };

    $scope.activeObj = $scope.objectList[0];
    $scope.updateTable_2($scope.activeObj); //initialize the data for table 2
  }
<tr ng-class="{selected: activeObj === obj }" ng-repeat="obj in objectList | filter:search" ng-click="updateTable_2(obj) ">
  <td>{{obj.prop}}</td>
</tr>

希望对你有所帮助