2014-02-07 42 views
0

选择的对象我有一个选择,我是人口和违约基于外部值:获取角选择

<select ng-model="course.instructor_id" ng-options="instructor.id as instructor.first_name for instructor in instructors"></select> 

我想我需要保持NG-模式和选项非常接近这个如此它会正确更新/默认课程模型,但我需要获取当前选定的教师对象的属性。

如何获取当前选择的对象?

我希望能够显示当前选择的教练的画面:

<img ng-src="selected_instructor.picture""/> 
+0

可以绑定到'selected_instructor'直接'<选择NG-模型= “selected_instructor” NG-选项=“C。 first_name for c in instructors“>'?或者你必须绑定到'课程' –

+0

问题是,我想保持模型。我已经标记了我认为是最优雅的解决方案。谢谢! – tommybananas

回答

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> 
2

从我已经看到了你的问题,你永远不会设置selected_instructor。这是我的解决方案的Fiddle

你的选择标签及其ng指令基本上是正确的。下面是我使用的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.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" 

      } 
     } 
    }); 

而且,奖励积分的人谁可以告诉大学我去了......(提示,它在加拿大最好的。)

+0

+1 for placehod.it。麦吉尔大学? ;) – klode