2014-09-01 58 views
-1

我有一個表格materials,當我點擊時,我想要顯示與該行有關的所有數據的表格。什麼是最好的方法來做到這一點?AngularJS - 從表格行顯示錶格

你可以看到下面

的index.html

<section ng-controller="materialController as materialCtrl"> 
    <table class="table table-hover"> 
     <th> Nombre </th> 
     <th> Descripción </th> 
     <tr ng-repeat="material in materials" ng-click="materialCtrl.openForm()"> 
      <td> 
       {{material.name}} 
      </td> 
      <td> 
       {{material.description}} 
      </td> 
     </tr> 
    </table> 
</section> 

控制器

app.controller("materialController", ["$scope", "$http", function($scope, $http){   

     $http.get('material').success(function(data){ 
      $scope.materials = data; 
     }); 

     this.openForm = function(){ 
      // Do something 
     }; 

}]); 
+0

爲什麼我有-1? – 2014-09-01 16:00:05

回答

0

首先,我想你可以由材料儲存在一些解決這個問題我的代碼範圍變量並使用它來確定哪一行已被點擊。其次,你在做這個控制器的事情是錯誤的,我會告訴你如何解決它。您直接參考了控制器,這可能不是最佳實踐。我建議你改變你的代碼看起來像這樣

app.controller("materialController", ["$scope", "$http", function($scope, $http){   

     $http.get('material').success(function(data){ 
      $scope.materials = data; 
     }); 
     $scope.selectedRow; 

     $scope.openForm = function(material){ 
      $scope.selectedRow = material; 
     }; 

}]); 

    <!--reference controller directly --> 
    <section ng-controller="materialController"> 
     <table class="table table-hover"> 
      <th> Nombre </th> 
      <th> Descripción </th> 
      <!-- reference openForm from scope --> 
      <tr ng-repeat="material in materials" ng-click="openForm(material)"> 
       <td> 
        {{material.name}} 
       </td> 
       <td> 
        {{material.description}} 
       </td> 
      </tr> 
     </table> 
    </section> 

然後對每種材料,如果你有某種形式要顯示或其他任何

<form ng-repeat="material in materials" ng-show="selectedRow == material"> 

此外,這是不是那麼重要,但更最佳實踐中,您應該將您的http請求提取到服務中。 https://docs.angularjs.org/guide/services

+0

我不認爲這是一個好主意爲每個「材質」創建一個表單。假設我有100000個「材料」,我只需要編輯一兩個。這將是非常低效的。我想以一種形式加載數據 – 2014-09-01 14:20:39

+0

@ Overflow012這就是你說的問題,無論這是你想要的。嘗試在未來更好地表達你的問題。您可以將selectedRow綁定到表單中的數據,而不是執行ngshow。 – MorningDew 2014-09-01 18:04:05

+0

謝謝!爲什麼這是一個糟糕的做法這樣做'this.openForm = function(){...}'? – 2014-09-01 20:07:32