[英]Undefined parameter in controller from ng-model
我有来自 API 的数据,用于显示表单。 表单包含级联选择字段。 我有 2 个函数可以用下一个选择的结果过滤我的数组,但我无法从 ng-model 读取属性。
例如,我选择第一个选项并获取它的 ID,然后我需要将该 ID 传递给控制器中的函数,该函数可以过滤数组以返回正确的选项。
API数据
section: { id: "111", name: "Section1" }
nomination: { id: "666", name: "Nomination2" }
category: { id: "999", name: "Category2"}
服务
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;
},
控制器
$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);
};
看法
<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>
我尝试从 API 数据中获取选定的 ID 并过滤我的数组。 鉴于我可以看到正确的 ID 为award.section.id,但是当我将此papameter 传递给我的控制器中的函数时,我得到了未定义的结果。 $scope.award.section.id 定义不足。
尝试将 select 的当前值传递给函数:
$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 = [];
};
并在 html 中:
<select
ng-model="sectionId"
ng-change="getSectionNominations(sectionId)"
ng-options="object.id as object.section for object in sections"
>
</select>
见答案在这里的传递变量参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.