gpt4 book ai didi

javascript - 在下拉列表中添加 ng-model 时删除空选项(AngularJS 1.4)

转载 作者:行者123 更新时间:2023-12-04 10:18:14 25 4
gpt4 key购买 nike

我目前正在做一个下拉菜单并通过 angular JS 获取数据,但是每当我添加 ng-model="email_mobile"时,它都会添加一个空字段
enter image description here我无法删除它,我尝试做正确的答案 here但我不认为它适用,因为我在 1 个数组中得到 2 个值:

JS

   $scope.configs = [
{'email': 'email@gmail.com',
'phone': '123',
'value': 'config1'},
];

$scope.getValue = function(){
$scope.value =$scope.email_mobile;
console.log($scope.value )
}

刀刃
        <select class="form-control" name="email_mobile" id="email_mobile" ng-model="email_mobile" ng-change="getValue()" required>
<option data-ng-repeat="x in configs" ng-if="x.email" value="@{{x.email}}" selected>@{{x.email}}</option>
<option data-ng-repeat="x in configs" ng-if="x.phone" value="@{{x.phone}}" selected>@{{x.phone}}</option>
</select>

还有一点,我的代码之所以这样,是因为我还需要获取 ng-model="email_mobile"的值。在变化。我只需要删除空值,同时仍然获得更改下拉列表的值

最佳答案

您可以通过以选项值的格式设置 select 的默认值来实现此目的:
$scope.email_mobile = "@" + $scope.configs[0].email;
检查下面的代码:

angular.module("myApp", [])
.controller("myCtrl", function($scope) {
$scope.configs = [{
'email': 'email@gmail.com',
'phone': '123',
'value': 'config1'
}];

$scope.email_mobile = $scope.configs[0].email;

$scope.getValue = function() {
$scope.value = $scope.email_mobile;
console.log($scope.value)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" name="email_mobile" id="email_mobile" ng-model="email_mobile" ng-change="getValue()" required>
<option data-ng-repeat="x in configs" ng-if="x.email" value="{{x.email}}" selected>{{x.email}}</option>
<option data-ng-repeat="x in configs" ng-if="x.phone" value="{{x.phone}}" selected>{{x.phone}}</option>
</select>
</div>

关于javascript - 在下拉列表中添加 ng-model 时删除空选项(AngularJS 1.4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60986918/

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