Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I define select option values in AngularJS
    text
    copied!<p>...while maintaining model bindings?</p> <p>I have a select menu like so:</p> <p><code>&lt;select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"&gt; &lt;/select&gt;</code></p> <p>That populates some text like so:</p> <p><code>&lt;span&gt;{{activeTask.title}}&lt;/span&gt;</code></p> <p>The <code>Projects</code> resource grabs some json here (which is working fine):</p> <pre><code>function TimerCtrl($scope, Projects) { $scope.projects = Projects.get({}, {isArray:true}, function(projects) { $scope.tasks = $scope.projects[0].tasks; $scope.activeProject = $scope.projects[0]; $scope.activeTask = $scope.tasks[0]; }); } </code></pre> <p>This is the <code>Projects</code> service (which is working fine as well):</p> <pre><code>angular.module('projectServices', ['ngResource']). factory('Projects', function($resource) { return $resource('data/projects.json', {}, { get: {method:'GET', isArray:true} }); }); </code></pre> <p>and this is the JSON (which is also fine):</p> <pre><code>[ { "title":"Chores", "url_title":"chores", "category":"Home", "tasks": [ {"title":"Cleaning", "url_title":"cleaning"}, {"title":"Yard Work", "url_title":"yard_work"}, {"title":"Walking the Dogs", "url_title":"url_title"} ] }, { "title":"Personal Website", "url_title":"personal_website", "category":"Work", "tasks": [ {"title":"Design", "url_title":"design"}, {"title":"Front End Dev", "url_title":"front_end_dev"}, {"title":"Node Dev", "url_title":"node_dev"}, {"title":"PHP Dev", "url_title":"php_dev"} ] } ] </code></pre> <p>Everything works fine with the numeric values that Angular automatically creates. My problem is...the values need to be the url-friendly string <code>task.url_title</code> but the option text should be <code>task.title</code>.</p> <p>Any help would be greatly appreciated. I want to go drink a beer!</p> <p><strong>So, here's the solution I went with:</strong></p> <p>I used the <code>task</code> object itself as the value like so:</p> <pre><code>&lt;select class="form-control" ng-model="activeTask" ng-options="task as task.title for task in tasks"&gt; </code></pre> <p>This allowed me to easily bind the span value to display the task <code>title</code>, not <code>url_title</code>:</p> <pre><code>&lt;span&gt;{{activeTask.title}}&lt;/span&gt; </code></pre> <p>Thanks to @sza for his pointing me in the right direction. His suggestions are in the comments of the correct answer.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload