我正在使用angular,我正在尝试使用我设法做的一系列对象来填充html选择元素。我要做的下一件事是使用$ scope变量设置selected,该变量表示选项文本(而不是值),以便它将绑定。
var egApp = angular.module("egApp", []);
egApp.controller('ExampleCtrl', function($scope){
/*
$http.get('getLanguages.php')
.success(function(response){
$scope.Languages = response;
});
*/
$scope.Languages = [
{"id":"1", "name":"Java"},
{"id":"2", "name":"Python"},
{"id":"3", "name":"PHP"},
{"id":"4", "name":"SQL"}
];
/*
$http.get('getCode.php', {"params": {"CodeId": myCodeId}})
.success(function(response){
$scope.info = response;
});
*/
$scope.info = {
"id": "3",
"lang": "PHP",
"title": "hello world",
"content": "\<?php\n\techo \"hello world\";\n?\>"
};
});
<div ng-app="egApp" ng-controller="ExampleCtrl">
<label>Id:</label><input type="text" ng-model="info.id" readonly/><br />
<label>Title:</label><input type="text" ng-model="info.title" /><br />
<label>Language:</label><select
ng-model="info.lang"
ng-options="L.name for L in Languages track by L.id"></select><br/>
<textarea>{{info.content}}</textarea>
</div>
这里是一个jsfiddle的链接,我已经做了更好地说明我想做的事情 https://jsfiddle.net/jpsh/ke2abu1t/
我想要的结果是“PHP”将是所选文本,当所选项目发生更改时,它会将$ scope.info.lang设置为所选选项文本。
答案 0 :(得分:2)
您需要将ng-options更改为如下所示:
ng-options="L.name as L.name for L in Languages"
“L.name as L.name”指定您要显示名称,并将名称绑定到info.lang属性。