我有一个像这样的选择选项:
<select ng-init="filterSelected = getItems.data.key"
ng-model="filterSelected"
ng-options="data.key as data.label for data in getItems.data" ></select>
我在其中解析一个json,它返回一些结果,显示为此select中的项目。这不是问题,我可以显示项目,但我无法更改它们。它停留在第一个,即使我尝试更改值仍然显示第一个。顺便说一句,我在我的javascript中有一个函数:
$scope.getObjects = function(){
for (var i = 0; i < $scope.getItems.data.length; i++) {
if($scope.filterSelected = $scope.getItems.data[i].key){
return $scope.getItems.data[i].objects;
}
}
};
这个函数需要因为我必须在我的json中找到正确的对象循环,如下所示:
"data": [
{
"label": "first",
"objects": [
{
"name": "firstObj",
"attributes": [
{
----,
----,
----
},
{
----,
----,
----
}
]
}
],
"key": "1"
},
---
---
所以我可以找到我选择的“对象”,我可以找到该对象的正确属性。问题是卡住了。结果是正确的,但它只显示第一个..也许模型有问题?
答案 0 :(得分:1)
您可以在ngOptions
中选择要选择的值在您的代码中选择 key 字段,然后按键尝试获取对象,但您可以立即获取对象
<select
ng-model="filterSelected"
ng-options="data.objects as data.label for data in getItems.data" ></select>
var myApp = angular.module('myApp', []);
myApp.controller("mycontroller", ["$scope", "$http",
function($scope, $http) {
$scope.getItems = {
"data": [{
"label": "first",
"objects": [{
"name": "firstObj",
"attributes": [{
"att1": "asd",
"att2": "asd2"
}, {
"att3": "asd3",
"att4": "asd4"
}]
}],
"key": "1"
}, {
"label": "second",
"objects": [{
"name": "secondObj",
"attributes": [{
"att1": "asd",
"att2": "asd2"
}, {
"att3": "asd3",
"att4": "asd4"
}]
}],
"key": "2"
}]
};
$scope.filterSelected = $scope.getItems.data[0].objects;
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='mycontroller'>
<select ng-model="filterSelected" ng-options="data.objects as data.label for data in getItems.data"></select>
{{filterSelected}}
</div>
&#13;
UPDATE 用于评论,因此您需要保存完整对象,而不仅仅是对象,标签或键属性。
<select
ng-model="filterSelected"
ng-options="data.label for data in getItems.data" ></select>
var myApp = angular.module('myApp', []);
myApp.controller("mycontroller", ["$scope", "$http",
function($scope, $http) {
$scope.getItems = {
"data": [{
"label": "first",
"objects": [{
"name": "firstObj",
"attributes": [{
"att1": "asd",
"att2": "asd2"
}, {
"att3": "asd3",
"att4": "asd4"
}]
}],
"key": "1"
}, {
"label": "second",
"objects": [{
"name": "secondObj",
"attributes": [{
"att1": "asd",
"att2": "asd2"
}, {
"att3": "asd3",
"att4": "asd4"
}]
}],
"key": "2"
}]
};
$scope.filterSelected = $scope.getItems.data[0];
}
]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='mycontroller'>
<select ng-model="filterSelected" ng-options="data.label for data in getItems.data"></select>
<div>objects: {{filterSelected.objects}}</div>
<div>key: {{filterSelected.key}}</div>
</div>
&#13;