Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript AngularJS选择必填项_Javascript_Angularjs_Validation - Fatal编程技术网

Javascript AngularJS选择必填项

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设置验证时遇到一些问题。代码读起来像

HTML

我尝试过不同的方法,比如在
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;
    }
});