Jpsh
Jpsh

Reputation: 1726

AngularJS set selected option by text

I am using angular and am trying to populate an html select element with an array of objects witch I have managed to do. the next thing I want to do is set the selected with a $scope variable that represents an options text (not value) so that it will bind.

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>

here is a link to a jsfiddle I have made to better illustrate what I Want to do https://jsfiddle.net/jpsh/ke2abu1t/

my desired result is that "PHP" would be the selected text and when the selected item changes it would set $scope.info.lang to the selected option text.

Upvotes: 0

Views: 1189

Answers (1)

Matt Nordberg
Matt Nordberg

Reputation: 46

You'll want to change ng-options to look like this:

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

"L.name as L.name" specifies that you want to display the name and also bind the name to the info.lang property.

Upvotes: 2

Related Questions