gpt4 book ai didi

javascript - AngularJS 选择必需

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

我在设置选择验证时遇到一些问题。代码如下:

HTML

<form name="customerForm" novalidate="novalidate" data-ng-submit="submit()">
<li class="has-error" data-ng-if="customerForm.country.$error.required">
{{ 'CountryRequired' | translate }}
</li>

<label for="ddlCountries">{{ 'Country' | translate }}</label>
<select id="ddlCountries" name="country" class="form-control"
data-ng-model="selectedCountry"
data-ng-options="option.text for option in countries track by option.id"
data-ng-change="countryChange()" required="required">
<option value="" selected="selected">{{ 'SelectCountry' | translate }}</option>
</select>
</form>

JS Controller

$scope.countries = [];
countryService.getCountries().then(function (results) {
$scope.countries = results.data;
}, function (error) {
console.log(error.data.message);
});

$scope.$watch('customer.country', function (id) {
// Select the value on the dropdown list
$scope.selectedCountry = { id: id };
});

$scope.countryChange = function () {
$scope.customer.country = $scope.selectedCountry.id;
};

$scope.submit = function () {
if ($scope.customerForm.$valid) {
customerService.postCustomerForm($scope.customer).success(
function (data, status, headers, config) {
/*success callback*/
}).error(function (data, status, headers, config) {
alert("Submitting form failed!");
});
} else {
console.log("Invalid fields");
}
};

我尝试过不同的方法,例如在 select 上设置 selected="selected" 但没有成功。还尝试了 requiredng-required 但没有运气。

我是否遗漏了什么或做错了什么?

最佳答案

问题是您重置了选择模型,因此您定义的原始模型被新模型替换。看这段代码:

$scope.$watch('customer.country', function(id) {
$scope.selectedCountry = {id: id};
});

在此代码中,您使用全新对象覆盖$scope.selectedCountry,因此用于设置表单验证的模型将被销毁,并且永远不会出现新的验证构建。

在您的情况下,您可以像这样更新 selectedCountry 模型:

$scope.$watch('customer.country', function(id) {
if (id) {
$scope.selectedCountry.id = id;
}
});

但更好的是,一起删除水,您不需要它,因为您有 ngChange 指令,您可以在其中更新 selectedCountry.id

演示: http://plnkr.co/edit/CXDRdRYxZn38FnanOqid?p=preview

关于javascript - AngularJS 选择必需,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175316/

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