AngularJS - 从表格行显示表格

时间:2014-09-01 02:03:59

标签: angularjs

我有一个materials的表格,当我点击时,我想显示一个包含与该行相关的所有数据的表单。这样做的最佳方法是什么?

您可以在下面看到我的代码

的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
       };

}]);

1 个答案:

答案 0 :(得分: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