gpt4 book ai didi

javascript - 来自 ng-model 的 Controller 中的未定义参数

转载 作者:行者123 更新时间:2023-11-30 19:25:42 25 4
gpt4 key购买 nike

我从 API 获得了数据,我用它来显示表单。表单包含级联选择字段。我有 2 个函数可以根据下一次选择的结果过滤我的数组,但我无法从 ng-model 中读取属性。

例如,我选择第一个选项并获取它的 ID,然后我需要将该 ID 传递给我在 Controller 中的函数,它可以过滤数组以返回正确的选项。

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;
},

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);
};

查看

<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 并过滤我的数组。在 View 中,我可以看到正确的 ID 作为 award.section.id,但是当我将此 papameter 传递到我的 Controller 中时,我得到未定义的结果。$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>

查看答案 here将变量作为参数传递

关于javascript - 来自 ng-model 的 Controller 中的未定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56938733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com