2014-02-07 78 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