最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Populate table data with $http.get on dropdown option selected in Angular - Stack Overflow

programmeradmin1浏览0评论

I am new to Angular and would like to learn how to acplish this task below:

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.

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:

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

I am new to Angular and would like to learn how to acplish this task below:

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.

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:

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>
}
Share Improve this question edited Oct 7, 2015 at 16:05 Aaron asked Oct 6, 2015 at 22:17 AaronAaron 1,0713 gold badges14 silver badges22 bronze badges 7
  • It is okay for me. But you could define services (+angula-resource) to retrieve JSON/XML data. – felipsmartins Commented Oct 6, 2015 at 22:26
  • @felipsmartins I don't think I quite understand what you are asking. Are you wanting me to find a neutral data source for pulling in JSON data? So we can mess with the same data? – Aaron Commented Oct 6, 2015 at 22:32
  • Read more about angular services and how the controller should play it's row in a view. For instance, the controller should not make the $http call, a service should. – Fernando Pinheiro Commented Oct 6, 2015 at 22:33
  • use ng-change and make request inside the corresponding controller function – charlietfl Commented Oct 6, 2015 at 22:42
  • 2 have a look at this example. Hope this helps. :) – Fracedo Commented Oct 6, 2015 at 22:44
 |  Show 2 more ments

2 Answers 2

Reset to default 1

No need for multiple controllers, and you'll need to bind to ngChange. Observe the following example, specifically, the binding to 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 remend 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


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.

You should also use ng-change to invoke table column name info call

Try this

in 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,

<!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="[email protected]" src="https://cdnjs.cloudflare./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.

发布评论

评论列表(0)

  1. 暂无评论