我在为选择设置验证时遇到一些问题。代码看起来像
的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控制器
$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");
}
};
我尝试过其他操作,例如在
selected="selected"
上设置select
,但是没有用。还尝试了required
和ng-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;
}
});
但是更好的是,一起删除所有的wather,因为有了
ngChange
指令即可在其中进行更新,因此不需要它。演示:http://plnkr.co/edit/CXDRdRYxZn38FnanOqid?p=preview