【发布时间】:2016-04-05 12:04:53
【问题描述】:
我正在尝试根据文档字段的键并在 AngularJS 中使用 ng-if 属性来生成动态表单。
例如:
- If field name is "name|string" then populate textfield
- If field name is "name|select" then populate dropdownlist
- If field name is "name|datepicker" then populate datepicker
以下是代码:
<div class="form-group" ng-repeat="(index, formVal) in providerModelData" ng-if="!$first">
<label>{{mySplit(index,0) | uppercase}}</label>
<div ng-if="!mySplit(index,1)">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'datepicker'">
<input type="text" class="form-control" ng-model="providerModelData[index]">
</div>
<div ng-if="mySplit(index,1) == 'select'">
<select class="form-control" ng-init="getDropdownData(index,colName)" ng-options="dropdown._id for dropdown in dropdownData[colName]">
<option value="">Select</option>
</select>
</div>
</div>
控制器:
$scope.mySplit = function(string, nb) {
var array = string.split('|');
return array[nb];
}
textfields 工作正常并填充数据,但我在填充下拉字段时遇到问题。
示例:我的 mongodb 文档中有两个下拉字段,即 city|select 和 state|select
我正在尝试使用 ng-options 通过传递 index 和 colName(文档名称)来调用函数来填充下拉列表,但它不起作用。
以下是代码:
$scope.dropdownData = {};
$scope.getDropdownData = function (query, colName) {
$http.get('/getdropdowndata/', {
params: {
query: query,
colName: colName
}
}).success(function (response) {
$scope.dropdownData[colName] = response;
});
};
快递:
router.route('/').get(function (req, res) {
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
console.log(query.query);
db.collection(query.colName).aggregate([{
"$group":{
"_id":"$"+query.query
}
}],function (err, docs) {
console.log(docs);
res.json(docs);
});
});
最初我尝试在ng-repeat 中调用函数,但它进入了无限循环。后来我尝试了ng-init 选项,但它只调用或初始化一次,这在我的情况下不起作用。在这里,我需要动态调用函数,并根据我想要填充不同字段的下拉列表。
任何帮助将不胜感激。
【问题讨论】:
-
问题出在
"dropdown._id for dropdown in getDropdownData(index,colName)"。getDropdownData是一个函数,而不是一个集合。您需要将该函数调用的结果保存到范围变量,并将该变量用于ng-options -
如何在角度表达式中使用 $scope 变量?因为我是从我的
view而不是控制器调用函数 -
您能否提供 JSBin 或 Codepen 与您的代码,当您硬编码服务器 I.getDropDownApi 的响应而不发送请求并从服务器接受它时会发生什么??
-
如果您可以提供来自服务器的响应结构和 providerModelData 的内部结构以及每个请求和响应结构,那将会很有帮助..?
标签: javascript angularjs mongodb mean-stack