Javascript AngularJS选择必填项
我在为select设置验证时遇到一些问题。代码读起来像 HTML 我尝试过不同的方法,比如在Javascript AngularJS选择必填项,javascript,angularjs,validation,Javascript,Angularjs,Validation,我在为select设置验证时遇到一些问题。代码读起来像 HTML 我尝试过不同的方法,比如在select上设置selected=“selected”,但没有成功。还尝试了required和ng required,但运气不佳 我是缺少了什么还是做错了?问题是您重置了“选择模型”,以便将您定义的原始模型替换为新模型。看看这段代码: $scope.$watch('customer.country', function(id) { $scope.selectedCountry = {id: id
select
上设置selected=“selected”
,但没有成功。还尝试了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
指令,可以在其中更新selectedCountry.id
演示:然后如何处理所选值?如果我使用
customer.country
中的值,在我选择一个值后,int将更改为一个对象,可能有一个比$watch和更改功能更好的方法。如果需要watch,请使用它,只是不要重新指定整个模型对象。
$scope.$watch('customer.country', function(id) {
$scope.selectedCountry = {id: id};
});
$scope.$watch('customer.country', function(id) {
if (id) {
$scope.selectedCountry.id = id;
}
});