AngularJS通过文本设置选定的选项


AngularJS set selected option by text

我正在使用角度,并试图用我设法做到的对象数组填充 html select 元素。 接下来我要做的是用表示选项文本(不是值)的 $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设置为所选选项文本。

您需要

将ng选项更改为如下所示:

ng-options="L.name as L.name for L in Languages"

"L.name L.name"指定要显示名称并将名称绑定到 info.lang 属性。