Reputation: 5736
I have a select that I'm populated and defaulting based on an outside value:
<select ng-model="course.instructor_id" ng-options="instructor.id as instructor.first_name for instructor in instructors"></select>
I think I need to keep the ng-model and options pretty close to this so it updates/defaults the course model correctly but I need to grab a property of the currently selected instructor object.
How do I get the currently selected object for this select?
I want to be able to show the picture of the currently selected instructor:
<img ng-src="selected_instructor.picture""/>
Upvotes: 0
Views: 415
Reputation: 11061
If you need to update the course model when a new instructor is selected, you can use
$scope.$watch
to watch for changes of the selected_instructor value.
Here is an example:
app.controller("instructorCtrl", function($scope) {
$scope.course = {
instructor_id: null
};
$scope.instructors = [{
id: 1,
firstName: "Stefano",
lastName: "Baroni",
imageUrl: "http://placehold.it/300x150"
}, {
id: 2,
firstName: "Elisa",
lastName: "Molinari",
imageUrl: "http://placehold.it/150x150"
}, {
id: 3,
firstName: "Stefano",
lastName: "De Gironcoli",
imageUrl: "http://placehold.it/200x150"
}]
$scope.$watch(
"selected_instructor",
function(newValue, oldValue) {
if (newValue === oldValue) {
return;
}
$scope.course.instructor_id = newValue.id;
}
)
})
html template:
<div ng-controller="instructorCtrl">
<img src="{{selected_instructor.imageUrl}}" />
<br/>
<select ng-model="selected_instructor" , ng-options="instructor.lastName for instructor in instructors">
<option value="">-- choose instructor--</option>
</select>
<br/><label>Currently selected instructor:</label>{{selected_instructor}}
<br/><label>Course:</label> {{ course }}
</div>
Upvotes: 2
Reputation: 45
From what I've seen of your question, you are never setting the selected_instructor. Here's a Fiddle of my solution for you.
You were basically correct in your select tag and its ng-directives. Here's what I used for the HTML template:
<div ng-app="demoApp" ng-controller="demoCtrl">
<select ng-model="instructor" ng-options="teacher.lastName for teacher in instructors">
{{teacher.lastName}}
</select>
<img src="{{instructor.imageUrl}}" />
</div>
For the Angular base, I made a dummy app and controller as such:
angular.module('demoApp', []);
angular.module('demoApp')
.controller('demoCtrl', function ($scope) {
$scope.instructor = null;
$scope.instructors = {
{
firstName: "Scott",
lastName: "Bohle",
courses: ["CHEM110", "CHEM222"],
imageUrl: "http://placehold.it/300x150"
},
{
firstName: "Arial",
lastName: "Fenster",
courses: ["CHEM180"],
imageUrl: "http://placehold.it/150x150"
}
}
});
Also, bonus points to anyone who can tell what University I went to... (Hint, it's the best in Canada.)
Upvotes: 2