AngularJS选择必需

时间:2015-03-20 20:29:44

标签: javascript angularjs validation

我在为select设置验证方面遇到了一些问题。代码读起来像

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但不起作用。还没有运气,尝试了requiredng-required

我错过了什么或做错了吗?

1 个答案:

答案 0 :(得分:0)

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

$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