我是AngularJS的新手,我想编写一个flexibile函数来填充带有数据库表内容的select。我已经可以填充选择,但是我无法为它设置第一个值。
我的代码:
HTML:
<div id="super-regional-modal" ng-controller="RegionalController">
<form name="regionalform" id="regionalform">
<div class="form-group">
<div class="row">
<div class="input-field col s12">
<span style="color:#DA1022;">* </span><label for="regionalInfoTipoRegional">Label Test</label>
<select class="form-control" id="regionalInfoTipoRegional" name="regionalInfoTipoRegional" ng-model="regionalInfo.tipoRegional" ng-init="regionalInfo.tipoRegional = populateSelect('select * from wrk_tests')" ng-options="tiporegional as tiporegional.cidade for tiporegional in populate_select_output track by tiporegional.id" ng-required="true"></select>
</div>
</div>
</div>
</form>
</div>
JS:
'use strict';
angular.module("acsApp").controller("RegionalController", ["$scope", "$http", "$state", "$stateParams", "$timeout", "$sce", "toaster", function ($scope, $http, $state, $stateParams, $timeout, $sce, toaster){
$scope.populateSelect = function(sqlselect){
$http.post("modulos/sistema/php/sys/fillDB.php", {"sqlselect" : sqlselect}
).success(function(data, status, headers, config){
$scope.populate_select_output = data.records;
}).error(function(data, status, headers, config){
console.error(data);
});
}
PHP:
<?php
header("Access-Control-Allow-Origin: *");
include($_SERVER["DOCUMENT_ROOT"]."/".explode("/",$_SERVER["PHP_SELF"])[1]."/functions.php");
include($_SERVER["DOCUMENT_ROOT"]."/".explode("/",$_SERVER["PHP_SELF"])[1]."/clsConnection.php");
$cls_database = new Database();
$db = $cls_database->getConnection();
$data = json_decode(file_get_contents("php://input"));
$sqlselect = $data->sqlselect;
$stmt = $db->prepare($sqlselect);
$stmt->execute();
$num = $stmt->rowCount();
$arr = array();
if($num>0){
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
}
}
header("Content-Type: application/json; charset=UTF-8");
echo json_encode(['records' => $arr]);
?>
感谢任何帮助。抱歉我的英语不好。提前谢谢。
答案 0 :(得分:1)
首先,您需要在控制器中为regionalInfo
定义一个起始值:$scope.regionalInfo = {};
,然后将任何检索到的记录分配给regionalInfo.tipoRegional
:
'use strict';
angular.module("acsApp").controller("RegionalController", ["$scope", "$http", "$state", "$stateParams", "$timeout", "$sce", "toaster", function ($scope, $http, $state, $stateParams, $timeout, $sce, toaster){
$scope.regionalInfo = {};
$scope.populateSelect = function(sqlselect){
$http.post("modulos/sistema/php/sys/fillDB.php", {"sqlselect" : sqlselect}
).success(function(data, status, headers, config){
$scope.populate_select_output = data.records;
$scope.regionalInfo.tipoRegional = $scope.populate_select_output[0]; // or 1, 2, etc...
}).error(function(data, status, headers, config){
console.error(data);
});
}
并且ng-init
可以更改为:
ng-init="populateSelect('select * from wrk_tests')"