我有一个以这种格式返回JSON元素的API
{
"XYZ": ["xyz","abc"],
"ABC": ["cde","abc"],
"CDE": ["bla","blla"]
}
我必须在下拉列表中添加这些元素,因为该HTML代码是
<select class="ui search dropdown selection" ng-options="v for (v,k) in <API returns JSon>" style ="select:invalid { color: gray; }" ng-model="xyz">
<option value="" disabled selected hidden>Select Element</option>
</select>
<button type="button" class="btn btn-primary" ng-click='saveData(xyz)'>Save</button>
我的指示是
angular.module('member').directive('memberDirective',function(){
templateUrl: "../../XYZ/xyz.html",
controller: 'appConttroller',
link: function($scope){
$scope.saveData = function(data){
console.log(data);
}
}
});
现在主要的问题是即使用户从下拉列表中选择任何一个值并单击保存按钮,在控制台日志中我也可以看到其对应的值。
例如,如果用户选择 XYZ 并点击保存按钮,则在控制台日志中我可以看到 [“xyz”,“abc”] 。但我希望用户选择的价值,而不是相应的价值。 所以有人可以建议如何实现这一目标吗?对于我的程序中的所有其他选择元素,我从ng-model获得的值只是不知道为什么在这里出错了?
答案 0 :(得分:1)
您应该使用select as
指令中的ngOptions
语法,如下所示:
<select class="ui search dropdown selection" ng-options="v as v for (v,k) in json" style ="select:invalid { color: gray; }" ng-model="xyz">
<option value="" disabled selected hidden >Select Element</option>
</select>
(function() {
angular.module('MyApp', [])
.controller('MyController', MyController);
MyController.$inject = ['$scope']
function MyController($scope) {
$scope.json = {
"XYZ": ["xyz", "abc"],
"ABC": ["cde", "abc"],
"CDE": ["bla", "blla"]
}
$scope.saveData=function(data){
console.log(data);
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
<div ng-controller="MyController">
<select class="ui search dropdown selection" ng-options="v as v for (v,k) in json" style="select:invalid { color: gray; }" ng-model="xyz">
<option value="" disabled selected hidden>Select Element</option>
</select>
<p>Value of ngModel: {{xyz}}</p>
<button type="button" class="btn btn-primary" ng-click='saveData(xyz)'>Save</button>
</div>
</div>