我是 Angular 的新手,我遇到了一个问题,我没有找到可以帮助我的答案,如果有人可以,谢谢。 :)
我有一个像这样的json:
"items": [
{
"post_type": "release",
"label": "Releases"
},
{
"post_type": "news",
"label": "Notícias",
"options": [
{
"id": 1,
"name": "Galeria de Fotos"
},
{
"id": 2,
"name": "Agência de Notícias"
},
{
"id": 3,
"name": "Rádio"
},
{
"id": 4,
"name": "TV"
}
]
},....
我得到的数据如下:
var _preparingPostTypes = function ($scope) {
$scope.post_types = [];
PostTypeService.getPostTypes().then(function (data) {
$scope.post_types = data.data;
});
};
我想要做的是创建 2 个选择,第一个 - 使用 post_type ('release', 'news') ,第二个选择使用 post_type 中的 'options' 数组,仅当选择一个选项时才可见数组中的“选项”如“新闻”。我做了这样的事情,我可以像魅力一样获得 post_type,但我不知道如何继续:
<div class=form-group>
<label>Pesquisar em:</label>
<select title="Pesquisar em:" class="form-control select-post-type"
ng-model="widget.post_type"
ng-options="item.post_type as item.label for item in post_types.items"></select>
</div>
编辑:
在我的请求中,我需要从第一个选择将 post_type 字符串传递到服务器,因此 ng-options 是:
ng-options="item.post_type as item.label for item in post_types.items
不是:
ng-options="item as item.label for item in post_types.items
谢谢大家!
最佳答案
您可以将 ng-change 添加到调用加载选项的函数的第一个选择
<select title="Pesquisar em:" class="form-control select-post-type"
ng-model="widget.post_type"
ng-options="item as item.label for item in post_types.items" ng-change="typeChanged()"></select>
该函数将在 $scope.options 内加载所选类型选项。然后在第二个选择中迭代 $scope.options
<小时/>更新:
我尚未测试代码,但它可能会指导您
选择:
<select title="Options:" class="form-control select-post-type"
ng-model="widget.option"
ng-options="option as option.name for option in options">
Change函数(当第一个select的值发生变化时触发,因此它将有责任加载所选的post_type的选项):
$scope.typeChanged = function() {
for (var i = 0; i < $scope.post_types.items.length; ++i) {
if ($scope.post_types.items[i].label == $scope.widget.post_type) $scope.options = $scope.post_types.items[i].options || [];
}
}
关于javascript - angularjs - 基于先前选择选项的嵌套 json 的 ng-options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442061/