2015-08-21 33 views
0

我在AngularJS中有一個表單,其中一個下拉列表的選項取決於第一個選擇的選項。一個ng選項取決於在另一箇中選擇什麼 - AngularJS

<select ng-options="obj.name for obj in institutions track by obj.id" ng-model="newUser.institution"> 
</select> 

<input type="text" name="email" ng-model="newUser.email"> 

<!-- DEPENDENT on what is selected in the previous dropdown --> 
<select ng-options="obj.name for obj in organizations track by obj.id" ng-model="newUser.associatedOrg"> 
</select> 

機構都裝滿了從數據庫中的可用機構的蝙蝠。即在控制器做過這樣的:

function populate() { 
    return Institutions.all().then(function (institutions) { 
     $scope.institutions = institutions; 
     return institutions; 
    }); 
} 

// at the end of the controller 
populate(); 

然而,在第二個下拉的「組織」是基於他們的父表的機構,所以我需要一個選項後做類似的東西$scope.organizations = institution.memberOrganizations;控制器從第一個下拉列表中選擇。

現在,只是爲了確保工作的事情,我做了一個名爲「加載組織」按鈕與ng-click此功能:

$scope.getOrganizationsOnCampus = function(institution) { 
    $scope.organizations = institution.memberOrganizations; 
}; 

這樣的作品,但是這是一個非常糟糕的用戶體驗。

所以我的問題是:每次選擇新機構時,如何更新$scope.organizations

我想這樣做不聽的DOM - 就像你在jQuery的會,因爲我知道這是對AngularJS最佳實踐方式

P.S.爲了進一步清晰起見,以下是之前的屏幕截圖,之後單擊「加載組織」按鈕以加載所選機構的子組織。這是我希望每次在上一個選項中選擇不同機構時自動執行的操作。

before you update child organizations

after you update child organizations - right now with a ghetto button click!

回答

3

你會用ng-change這樣的:

<select ng-options="obj.name for obj in institutions track by obj.id" ng-model="newUser.institution" ng-change"updateOrg(newUser.institution)"> 
</select> 

,然後在你的控制器,你有這樣的函數:

$scope.updateOrg = function(institution) { 
    $scope.organizations = institution.memberOrganizations; 
}; 
+1

這是一個這麼簡單!謝謝 :) –

相關問題