Angularjs 使用ng选项获取所选项目
我有一个带有属性的数组,我试图在加载时选择一个特定的数组 我的每个属性都有attribute object、type object和attributevalue数组 我想选择selected=true的属性值 这是我的角度代码:Angularjs 使用ng选项获取所选项目,angularjs,Angularjs,我有一个带有属性的数组,我试图在加载时选择一个特定的数组 我的每个属性都有attribute object、type object和attributevalue数组 我想选择selected=true的属性值 这是我的角度代码: app.controller('MainCtrl', function($scope) { $scope.profileData = { "attributes": [{ "attribute": { "id": 56,
app.controller('MainCtrl', function($scope) {
$scope.profileData = { "attributes": [{
"attribute": {
"id": 56,
"name": "Hárlitur",
"typeID": 5,
"visibleToUsers": true
},
"type": {
"id": 5,
"typeName": "list"
},
"attributeValues": [{
"id": 109,
"attributeID": 56,
"value": "Ljós",
"chosen": true
}, {
"id": 110,
"attributeID": 56,
"value": "Dökkur",
"chosen": false
}],
"valueText": null
}]};
$scope.changeValue = function changeValue(attribute, value) {
alert(JSON.stringify({"attributeID":attribute.attribute.id, "type": attribute.type.typeName, "value":value.id}));
};
});
<div ng-repeat="attribute in profileData.attributes">
<select ng-change="changeValue(attribute, attributeValue)" ng-options="item.id as item.value for item in attribute.attributeValues" ng-model="attributeValue.id"></select>
</div>
这是我的HTML代码:
app.controller('MainCtrl', function($scope) {
$scope.profileData = { "attributes": [{
"attribute": {
"id": 56,
"name": "Hárlitur",
"typeID": 5,
"visibleToUsers": true
},
"type": {
"id": 5,
"typeName": "list"
},
"attributeValues": [{
"id": 109,
"attributeID": 56,
"value": "Ljós",
"chosen": true
}, {
"id": 110,
"attributeID": 56,
"value": "Dökkur",
"chosen": false
}],
"valueText": null
}]};
$scope.changeValue = function changeValue(attribute, value) {
alert(JSON.stringify({"attributeID":attribute.attribute.id, "type": attribute.type.typeName, "value":value.id}));
};
});
<div ng-repeat="attribute in profileData.attributes">
<select ng-change="changeValue(attribute, attributeValue)" ng-options="item.id as item.value for item in attribute.attributeValues" ng-model="attributeValue.id"></select>
</div>
这是我的宝物:
我不知道这是否是解决您问题的最佳方法,但它确实有效 我所做的只是创建一个函数来搜索选择为true的值集。找到该值后,我将范围模型设置为该属性值。然后我马上调用了这个函数
$scope.selectChosen = function selectChosen() {
var attrVals = $scope.profileData.attributes[0].attributeValues;
for (var i = 0; i < attrVals.length; i++) {
if (attrVals[i].chosen) {
$scope.attributeValue = attrVals[i];
break;
}
}
};
$scope.selectChosen();
$scope.selectselected=函数selectselected(){
var attrVals=$scope.profileData.attributes[0]。attributeValue;
对于(变量i=0;i
完整的plunker位于:我找到了一个更好的解决方案:
<div ng-repeat="attribute in profileData.attributes">
<select ng-model="attributeValue" ng-change="changeValue(attribute, attributeValue)">
<option value="">Select</option>
<option ng-repeat="obj in attribute.attributeValues" value="{{obj.id}}" ng-selected="obj.chosen">{{obj.value}}</option>
</select>
</div>
挑选
{{obj.value}}