0

I am trying to display a dropdown options generated from SQL and send back the selected value to flask. I managed to load the dropdown options but I could not get the selected value. The option selected is empty when I tried to display it in HTML.

How do i obtain the option selected and display it? Please help me. Thank you.

Flask

@app.route("/Test/")
def getColumns():
        cur = mysql.connection.cursor()
        cur.execute("select column_name from information_schema.columns where table_name ='vosmii_data'")
        rv = cur.fetchall()
        # Converting all data from unicode to ascii
        cleanRV = [[s.encode('ascii') for s in columnList] for columnList in rv]
        # Initialize a dictionary to convert the returned data as lists does not work with flask
        colDict = {}
        for item in cleanRV:
            colDict[item[0]] = item[0]
        #passing result to dataColumns as a json string
        return render_template('test.html', dataColumns=json.dumps(colDict))

HTML

<!DOCTYPE html>
<html ng-app="graphVisualization" lang="en" >
    <head>
         <title>Shipping Data Visualization</title>
         <script src="//code.jquery.com/jquery-2.2.1.min.js"></script>
        <script src="//netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
        <script src="{{ url_for('static', filename='app.js') }}"></script>
    </head>
    <body ng-init="init('{{ dataColumns }}')" ng-controller="GraphVisualizationController">
        <select ng-model="selectedFilter" >
            <option ng-repeat="filter in dataColumns">{% raw %} {{filter}} {% endraw %}</option>
            </select>
            <div>
            {% raw %}
            <h4> You have selected: {{ selectedFilter}} </h4>
            {% endraw %}
        </div>
        <footer class="footer">
            <p>&copy; Company 2015</p>
        </footer>
    </body>
</html>

AngularJS script

(function () {
  'use strict';

  angular.module('graphVisualization', [])

  .controller('GraphVisualizationController', ['$scope', '$log',
    function($scope, $log) {
        $scope.banner = "Flask AngularJS ";

        $scope.selectedFilter = "";
        $scope.dataColumns = null;

        $scope.init = function(html_metadata) {
            console.log(JSON.parse(html_metadata));
            $scope.dataColumns = JSON.parse(html_metadata);
        }
    }
  ]);

}());

1 Answers1

1

You need to provide a value for each option in a select. You can fix it by changing your option ng-repeat to the following:

<option ng-repeat="filter in dataColumns" ng-value="filter">{% raw %} {{filter}} {% endraw %}</option>

For my angularjs projects I prefer to use the following syntax for selects:

<select ng-model="model" ng-options="item.id as item.name for item in items">
    <option value="">Default Option</option>
</select>
BShaps
  • 1,344
  • 7
  • 17