简体   繁体   English

在Angular中选择的下拉选项中使用$ http.get填充表数据

[英]Populate table data with $http.get on dropdown option selected in Angular

I am new to Angular and would like to learn how to accomplish this task below: 我是Angular的新手,想学习如何完成以下任务:

I have a dropdown that contains a list of table names from a database. 我有一个下拉列表,其中包含数据库中的表名列表。 When a table name is selected from the drop down I want to make an HTTP GET call to a web API method which returns the list of column names in the selected table. 当从下拉列表中选择表名时,我想对Web API方法进行HTTP GET调用,该方法返回所选表中的列名列表。

HTML: HTML:

<div class="row">
    <div ng-app="myApp">
        <div class="col-lg-12">
            <h1>Table Information</h1>
            <hr />
            <div ng-controller="TableController" class="col-lg-6">
                <label>Select a Table:</label>
                <select id="tablename" ng-options="table.Name for table in tables track by table.Name" ng-model="data.selectedOption" class="form-control"></select>
            </div>
        </div>
        <div class="col-lg-12">
            <h1>{{data.selectedOption}}</h1>
            <hr />
            <div ng-controller="TableColumnController" class="col-lg-6">
                <table class="table">
                    <thead>
                    <tr>
                        <th>Column Name</th>
                        <th>Type</th>
                        <th>Max Characters</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr ng-repeat="tablecolumn in tablecolumns">
                        <td>
                            {{tablecolumn.Name}}
                        </td>
                        <td>
                            {{tablecolumn.Type}}
                        </td>
                        <td>
                            {{tablecolumn.MaxCharacters}}
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

Here is my JavaScript: 这是我的JavaScript:

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

app.controller('TableColumnController', function ($scope, $http) {
    $http.get('http://localhost:61475/api/SxTableInfo/',
    {
        params: {
            tablename: "smsn"
        }
    }).
    success(function (data, status, headers, config) {
        $scope.tablecolumns = data;
    }).
    error(function (data, status, headers, config) {
        alert("error!");
    });
});

app.controller('TableController', function ($scope, $http) {
    $http.get('http://localhost:61475/api/SxTableInfo/').
        success(function (data, status, headers, config) {
            $scope.tables = data;
        }).
        error(function (data, status, headers, config) {
            alert("error!");
        });
});

What is the best way to do this? 做这个的最好方式是什么?

Here is just an example of what it looks like: 以下是它的外观示例:

例

UPDATED CODE: 更新的代码:

          <div class="row" ng-app="myApp">
    <div ng-controller="ctrl">
        <div class="col-lg-12">
            <h1>Table Information</h1>
            <hr />
            <div class="col-lg-6">
                <label>Select a Table:</label>
                <select id="tablename"
                        ng-options="table.Name for table in tables track by table.Name"
                        ng-model="data.selectedOption"
                        ng-change="getColumns(data.selectedOption)"
                        class="form-control"></select>

            </div>
        </div>
        <div class="col-lg-12">
            <h1>{{data.selectedOption.Name}}</h1>
            <hr />
            <div class="col-lg-6">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Column Name</th>
                            <th>Type</th>
                            <th>Max Characters</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr ng-repeat="tablecolumn in tablecolumns">
                            <td>
                                {{tablecolumn.Name}}
                            </td>
                            <td>
                                {{tablecolumn.Type}}
                            </td>
                            <td>
                                {{tablecolumn.MaxCharacters}}
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

@section Scripts{
    <script>
        var app = angular.module('myApp', []);

        app.factory('tableService', ['$http', function ($http) {

                function getColumns(selection) {
                    $http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }).success(function (data) {
                        return data;
                    });
                }

                function getTables() {
                    $http.get('http://localhost:61475/api/SxTableInfo/').success(function (data) {
                        return data;
                    });
                }

                return { getColumns: getColumns, getTables: getTables }
            }]);

        app.controller('ctrl', ['$http', '$scope', 'tableService', function ($http, $scope, tableService) {

            $scope.tables = tableService.getTables();

            $scope.getColumns = function (selection) {
                $scope.tablecolumns = tableService.getColumns(selection.Name);
            }

        }]);

    </script>
}

No need for multiple controllers, and you'll need to bind to ngChange . 不需要多个控制器,您需要绑定到ngChange Observe the following example, specifically, the binding to getStuff ... 请注意以下示例,特别是绑定到getStuff ...

<select 
    id="tablename" 
    ng-options="table.Name for table in tables track by table.Name" 
    ng-model="data.selectedOption" 
    ng-change="getStuff(data.selectedOption)"
    class="form-control">
</select>

app.controller('ctrl', function ($scope, $http) {
    $scope.getStuff = function(selection) {
        $http.get('http://localhost:61475/api/SxTableInfo/', { 
            params: { tablename: selection }
        })
        .success(function (data, status, headers, config) {
            $scope.tablecolumns = data;
        });
    }
}

I would recommend moving this logic into an injectable service, most likely your next step. 我建议将此逻辑移植到可注射服务中,这很可能是您的下一步。 Something like... 就像是...

app.factory('TableService', ['$http', function($http) {
    function getMetaData(selection) {
        $http.get('http://localhost:61475/api/SxTableInfo/', { params: { tablename: selection } }
    }

    return { getMetaData: getMetaData }
}]);

app.controller('ctrl', ['$scope', 'TableService', function ($scope, TableService) {
    $scope.getStuff = function(selection) {
        TableService.getMetaData(selection).then(function(response) {
            $scope.tablecolumns = response.data;
        });
    }
}]);

Plunker Link - simplified demo Plunker Link - 简化演示


Edit per your example and updated code, give this a shot... 根据您的示例和更新的代码进行编辑,请试一试......

app.controller('ctrl',...

    tableService.getTables().then(function(response) {
        $scope.tables = response.data;
    });

    $scope.getColumns = function (selection) {
       tableService.getColumns(selection.Name).then(function(response) {
            $scope.tablecolumns = response.data
        });
    }

You should not use two controllers for this purpose, instead you can use a service or factory for $https request to get you data from the server. 您不应该为此目的使用两个控制器,而是可以使用服务或工厂来获取$ https请求以从服务器获取数据。

You should also use ng-change to invoke table column name info call 您还应该使用ng-change来调用表列名称信息调用

Try this 试试这个

in app.js 在app.js

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

app.factory('userFactory', ['$http', function($http) {
  var dataFactory = {};


  dataFactory.getTableNames = function() {
    /*$http.get('http://localhost:61475/api/SxTableInfo/').
           success(function (data, status, headers, config) {
               $scope.tables = data;
           }).
           error(function (data, status, headers, config) {
               alert("error!");
           });*/
    data = [{
      id: 1,
      tableName: 'table1'
    }, {
      id: 2,
      tableName: 'table2'
    }, {
      id: 3,
      tableName: 'table3'
    }];
    return data;
  }
  dataFactory.getColumnNames = function() {
    alert('implement your logic here . ');
    /*  $http.get('http://localhost:61475/api/SxTableInfo/',
        {
            params: {
                tablename: "smsn"
            }
        }).
            success(function (data, status, headers, config) {
                $scope.tablecolumns = data;
            }).
            error(function (data, status, headers, config) {
                alert("error!");
            });*/
  }
  return dataFactory;
}]);
app.controller('MainCtrl', ['$scope', 'userFactory', function($scope, userFactory) {
  $scope.name = 'World';


  $scope.items = userFactory.getTableNames();
  $scope.getColumnNames= function(){
    userFactory.getColumnNames();

  }

}]);

in HTML, 在HTML中,

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js" data-semver="1.4.6"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
       <select ng-change="getColumnNames()" ng-model="selectedItem" ng-options="item.tableName as item.tableName for item in items"></select>

  </body>

</html>

Plunker link for the same. Plunker 链接相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM