Reputation: 176
I've got data from API, which I use to display a form. Form contains cascading select fields. I've got 2 functions to filter my array with results for the next select, but I can't read property from ng-model.
For example I choose first option and get it's ID, then I need to pass that ID to my function in controller, which can filter an array to return proper options.
API DATA
section: { id: "111", name: "Section1" }
nomination: { id: "666", name: "Nomination2" }
category: { id: "999", name: "Category2"}
SERVICE
const allSections = [
{ id: '111', section: 'Section1' },
{ id: '222', section: 'Section2' },
{ id: '333', section: 'Section3' },
];
const allNominations = [
{ id: '555', sectionId: '111', nomination: 'Nomination1' },
{ id: '666', sectionId: '222', nomination: 'Nomination2' },
{ id: '777', sectionId: '333', nomination: 'Nomination3' },
];
const allCategories = [
{ id: '999', sectionId: '111', category: 'Category1' },
{ id: '888', sectionId: '222', category: 'Category2' },
{ id: '000', sectionId: '333', category: 'Category3' },
];
getSection() {
return allSections;
},
getSectionNomination(sectionId) {
const nominations = ($filter('filter')(allNominations, { sectionId }));
return nominations;
},
getNominationCategory(sectionId) {
const categories = ($filter('filter')(allCategories, { sectionId }));
return categories;
},
CONTROLLER
$scope.award = {};
$scope.sections = awards_service.getSection();
$scope.getSectionNominations = () => {
$scope.nominations =
awards_service.getSectionNomination($scope.award.section.id);
$scope.categories = [];
};
$scope.getNominationCategories = () => {
$scope.categories =
awards_service.getNominationCategory($scope.award.section.id);
};
VIEW
<select ng-model="award.section.id"
ng-change="getSectionNominations()"
ng-options="object.id as object.section for object in sections")
</select>
<select ng-model="award.nomination.id"
ng-change="getNominationCategories()"
ng-options="object.id as object.section for object in nominations")
</select>
<select ng-model="award.category.id"
ng-options="object.id as object.section for object in categories"
</select>
I try to get selected ID from API Data and filter my arrays. In view I can see the proper ID as award.section.id, but when I pass this papameter to function in my controller I get undefined result. $scope.award.section.id is underfined.
Upvotes: 1
Views: 139
Reputation: 19372
Try to pass current value of select to function:
$scope.sectionId = 0;
if ($scope.sections && $scope.sections[0]) {
$scope.sectionId = $scope.sections[0].id;
}
$scope.getSectionNominations = (sectionId) => {
if (!sectionId) return;
$scope.nominations = awards_service.getSectionNomination(sectionId);
$scope.categories = [];
};
and in html:
<select
ng-model="sectionId"
ng-change="getSectionNominations(sectionId)"
ng-options="object.id as object.section for object in sections"
>
</select>
See answer here in Pass variable as parameter
Upvotes: 1