我的Angular JS应用程序中有以下代码块。 (这是巨大代码的简化版本)
HTML
<form name="form-demo">
<input type="text" class="form-control" ng-model="modeldemo.date" ng-change="functiondemo1();"/>
<input type="text" class="form-control" ng-model="modeldemo.date" ng-change="functiondemo2();"/>
<select class="form-control" name="move" ng-model="modeldemo.move" ng-options="move.type for move in moveList" ng-required="true">
</select>
</form>
JS档案
app.controller('moveCtrl', function($scope, $http, NgTableParams, $filter, $timeout) {
$scope.moveList = {};
$scope.functiondemo2 = function() {
// get the data from server and assign to $scope.moveList
}
$scope.functiondemo1 = function() {
$scope.modeldemo.move = null;
}
}
当第一个输入框值更改时,应清除下拉列表。当第二个输入发生变化时,应加载下拉值。
但由于ng-required
属性在下拉列表中设置为true
,因此调用functiondemo1
时,会显示“此字段为必填项”错误。
所以我修改了functiondemo1
如下。
$scope.functiondemo1 = function1() {
$scope.modeldemo.move = null;
$scope.form-demo.move.$setValidity("required", true);
}
然后我在控制台中遇到以下错误。
angular.js:12477 TypeError: Cannot read property '$setValidity' of undefined
at b.$scope.functiondemo1 (http://localhost:8080/js/script.js:63:16)
at fn (eval at compile (http://localhost:8080/angular/angular.min.js:212:409), <anonymous>:4:590)
at b.$eval (http://localhost:8080/angular/angular.min.js:133:221)
at pre (http://localhost:8080/angular/angular.min.js:257:49)
at aa (http://localhost:8080/angular/angular.min.js:73:90)
at K (http://localhost:8080/angular/angular.min.js:61:354)
at g (http://localhost:8080/angular/angular.min.js:54:410)
at g (http://localhost:8080/angular/angular.min.js:54:433)
at g (http://localhost:8080/angular/angular.min.js:54:433)
我还检查了以下内容,但没有任何效果。
$scope.form-demo.move.$setPristine();
$scope.form-demo['move'].$setValidity("required", true);
有谁知道如何修复此错误?
答案 0 :(得分:0)
我认为您的问题可能是由表单名称中的短划线字符引起的。 javascript变量名称中不允许使用破折号(请参阅here),因此您的行
$scope.form-demo.move.$setValidity("required", true);
可能被解释为:
($scope.form) - (demo.move.$setValidity("required", true))
发生错误。
我已将您的示例转换为Stack代码段并且$ setValidation调用似乎按预期工作,您能否检查一下您是否发现与实际代码有任何其他市长差异?
var app = angular.module("demoApp", []);
app.controller('moveCtrl', function($scope){
$scope.moveList = [
{type: "type1", id: 1},
{type: "type2", id: 2},
{type: "type3", id: 3}
];
$scope.changeHandler = function () {
$scope.modeldemo.move = null;
$scope.formDemo.move.$setValidity("customRule", false);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demoApp" ng-controller="moveCtrl">
<form name="formDemo">
<input type="text" class="form-control" ng-model="modeldemo.date" ng-change="changeHandler();"/>
<input type="text" class="form-control" ng-model="modeldemo.date" ng-change="changeHandler();"/>
<select class="form-control" name="move" ng-model="modeldemo.move" ng-options="move.type for move in moveList" ng-required="true">
</select>
</form>
<p>The select's valid state is:</p>
<h1>{{formDemo.move.$valid}}</h1>
</div>
&#13;