代码之家  ›  专栏  ›  技术社区  ›  Ayush Goyal

将数据从HTML传输到外部javascript代码

  •  2
  • Ayush Goyal  · 技术社区  · 6 年前

    我在HTML代码中有一个下拉列表,我正在使用angular填充它。我需要下拉列表的选定值,并将其发送到Angular,以便Angular从数据库中获取数据并填充到相同的HTML页面中。下面是我的代码。

    索引文件

    <div ng-app="myApp" ng-controller="sourceController" >
        <select class = "mdb-select md-form "  aria-labelledby="dropdownMenuButton" id="sourcesByName">
            <option class ="dropdown-item"  ng-repeat="source in showsource">{{source}}  </option>
        </select>
    
    </div>
    

    索引文件

    var Report = angular.module('Report', []);
    Report.controller('mainController', function($scope, $http) {
        $scope.showdata = {}
    
    // I want data here
    
    // Get home page
     $http.get('/api/v1/table')
        .success(function(data) {
             $scope.showdata = data;
             console.log(data);
         })
         .error(function(error) {
             console.log('Error: ' + error);
         });
    });
    
    
    // Get all sources
    Report.controller('sourceController', function($scope, $http) {
    $scope.showsource =[];
    $http.get('/api/v1/sources')
       .success(function(data) {
          var l = data.length;
          data1=['Sources'];
          var i;
          for(i=0;i<l;i++){
             data1.push(data[i]["source"]);
          }
          $scope.showsource = data1;
        })
        .error(function(error) {
        console.log('Error: ' + error);
      });
    });
    

    我的HTML页面中有一个表,我希望根据下拉值填充它。

    提前谢谢

    1 回复  |  直到 6 年前
        1
  •  2
  •   Sarah    6 年前

    |建议您在选择菜单中添加一个ng模型属性,例如

    ng-model="selectedValue"
    

    这将保留所选的值,并且您可以使用 $scope.selectedValue 您还应该添加一个 ng-change 属性设置为“选择”菜单,以便在选择某个选项时调用函数。

    HTML选择菜单代码:

     <select class="mdb-select md-form" ng-model="selectedValue" ng-change="selectSource()" aria-labelledby="dropdownMenuButton" id="sourcesByName">
        <option class="dropdown-item"  ng-repeat="source in showsource">{{source}}  </option>
     </select>
    

    在主控制器中

    var Report = angular.module('Report', []);
    Report.controller('mainController', function($scope, $http) {
      $scope.showdata = {};
    
      $scope.selectSource = function(){
        //This function will be called whenever a new option is selected.
        //log the selectedValue to check it
        console.log($scope.selectedValue);
        //perform http request here with the selectedValue in order to retrieve
        //the corresponding data from the database.
        //Once the data is retrieved, we update the $scope.showdata variable. The view will be automatically updated.
      };
    
    });