【问题标题】:set default value in dynamic dropdown angularjs在动态下拉angularjs中设置默认值
【发布时间】:2021-10-28 08:41:55
【问题描述】:

请帮我解决我的问题我对angularjs有点新,我的问题是我需要能够在只有一个项目时在选择选项中设置默认值,因为它是一个动态选择选项,它有另一个包含许多项目的下拉列表,但没关系,当必须使用 ng-options 在选择选项中选择一个项目时需要什么

                    <select  class="form-control form"  ng-model="relatedTo" style="height: 40px;" ng-options="c.CUSTCODE as c.CUSTNAME + ' - ' + c.CUSTCODE for c in customers | filter:code" >  </select><span style="color:red" ng-show="type === 9 || type !== 9"></span>

ANGULARJS

                    $http.post('commandCenter.aspx/allCustomer', {}).then(
                        function onSuccess(response) {
                            $scope.customers = JSON.parse(response.data.d);
                            console.log($scope.customers); },
                        function onError(response) {
                            console.log('error !!! ');
                        });

图一 这张图没问题,因为他有很多物品清单。

图二只有一项时,必须默认或选中。

【问题讨论】:

  • 您可以在您的函数中检查选项数组的长度是否为 1。如果是这样,则将模型值设置为数组的第一项。您可以做的其他选择是在您的 html 中使用 ng-init 并始终选择数组的第一项,因此它可以是您的默认选择
  • @MrJami I've already done this but what really needs to be done when there's only one item in the select should be automatically selected.

标签: javascript angularjs


【解决方案1】:

@MrJami 说了什么。在类似的代码中

                $http.post('commandCenter.aspx/allCustomer', {}).then(
                    function onSuccess(response) {
                        $scope.customers = JSON.parse(response.data.d);
                        if ($scope.customers.length === 1) {
                          $scope.relatedTo = $scope.customers[0].CUSTCODE;
                        }
                        console.log($scope.customers); },
                    function onError(response) {
                        console.log('error !!! ');
                    });

【讨论】:

  • 它不适合我
  • 我的想法是修改选择部分,例如添加 ng-if 和控制器中没有的任何内容,但我不知道如何实现它。
  • 在模板中进行选择后的模型值是多少?据我所知,如果满足单个选项的条件,则需要在控制器中设置该值。
  • 您的代码现在可以工作了,感谢您的帮助,当我检查检查元素时,选项值已被选中,我这里唯一的问题是像这样删除第一个空白选项 我不知道为什么总是被选中。
猜你喜欢
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 2017-04-28
  • 2013-11-23
  • 2017-06-17
  • 1970-01-01
  • 2013-07-22
  • 2021-09-11
相关资源
最近更新 更多