对于您的第一个问题,md-select 的 ng-model 将对应于集合中选定的动物,因此在此示例中 $scope.model.selectedAnimal 将是您可以用来访问选定动物的变量。
<div ng-controller="SelectOptGroupController" class="md-padding selectdemoOptionGroups">
<div>
<h1 class="md-title">Select Animal</h1>
<div layout="row">
<md-select ng-model="model.selectedAnimal" placeholder="Animals" ng-change="getSpecies()">
<md-option ng-repeat="animal in model.animals" value="{{ animal }}">{{ animal }}</md-option>
</md-select>
<md-select ng-model="model.selectedSpecies" placeholder="Species">
<md-option ng-repeat="species in model.species" value="{{ species.animal_species }}">{{ species.animal_species }}</md-option>
</md-select>
</div>
</div>
</div>
至于您重复的 api 调用问题,您可以让数据库返回所有物种并管理 js 中的“活动”物种,或者使用服务来缓存每个请求,以便至少每个动物只会查询 api一次。这也将数据逻辑排除在控制器之外,使其可重用(以及在多个控制器/指令/服务之间轻松共享数据)。
app.controller('SelectOptGroupController', ['$scope', 'animalService', function($scope, animalService) {
$scope.model = {
animals: [],
species: [],
selectedAnimal: '',
selectedSpecies: {}
};
animalService.getAnimals().then(function(data){
$scope.model.animals = data;
});
$scope.getSpecies = function(){
animalService.getSpecies($scope.model.selectedAnimal).then(function(data){
$scope.model.species = data;
});
};
}]); //TYPO WAS HERE
app.factory('animalService', ['$http', '$q', function($http, $q){
var cache = {};
return {
getAnimals: function(){
return $http.get('api2.php').then(function(result) {
return result.data;
});
},
getSpecies: function(animal){
if(cache[animal]){
return $q.when(cache[animal]);
} else{
return $http({
url: 'whatever.php',
method: 'GET',
params: {
animal: animal
}
}).then(function(result){
cache[animal] = result.data;
return cache[animal];
});
}
}
};
}]);
如果您想一次性获取所有物种并仅在前端进行过滤,您可以执行以下操作:
app.controller('SelectOptGroupController', ['$scope', 'animalService', function($scope, animalService) {
$scope.model = {
animals: [],
species: [], //this will contain selected animals species
allSpecies: [], //this will contain all species for all animals
selectedAnimal: '',
selectedSpecies: {}
};
animalService.getAnimals().then(function(data){
$scope.model.animals = data;
});
animalService.getSpecies().then(function(data){
$scope.model.allSpecies = data;
});
$scope.getSpecies = function(){
//this filters out the species for the selected animal
$scope.model.species = $scope.model.allSpecies.filter(function(species){
return species.animal === $scope.model.selectedAnimal;
});
};
}]);
app.factory('animalService', ['$http', '$q', function($http, $q){
return {
getAnimals: function(){
return $http.get('api2.php').then(function(result) {
return result.data;
});
},
getSpecies: function(animal){
return $http.get('api3.php').then(function(result){
return result.data;
});
}
};
}]);