我有一个基于外部值填充和默认的选择:
<select ng-model="course.instructor_id" ng-options="instructor.id as instructor.first_name for instructor in instructors"></select>
我认为我需要保持ng-model和选项非常接近这一点,以便正确更新/默认课程模型,但我需要获取当前所选教师对象的属性。
如何获取此选择的当前所选对象?
我希望能够显示当前所选教师的照片:
<img ng-src="selected_instructor.picture""/>
答案 0 :(得分:2)
从我所看到的问题来看,你永远不会设置selected_instructor。这是我的解决方案Fiddle。
您的select标签及其ng-directives基本上是正确的。这是我用于HTML模板的内容:
<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>
对于Angular基础,我做了一个虚拟应用程序和控制器:
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"
}
}
});
此外,任何能告诉我去过哪所大学的人都可以获得奖励......(提示,这是加拿大最好的。)
答案 1 :(得分:2)
如果您需要在选择新教师时更新课程模型,则可以使用
$scope.$watch
监视selected_instructor值的更改。
以下是一个例子:
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模板:
<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>