首先,我对 Angular 还很陌生。我创建了一个在 HTML 中的 form-group div 中使用的指令。这包含所需的输入。该指令的目的是检查整个 div 是否将根据范围值显示。
从视觉上看,这按预期工作,但是...当将 ng-if 指令设置为 false 值时,表单提交仍然给出错误 当表单甚至不再包含该输入时,缺少所需的值。
这是我的代码:
// My Directive
app.directive("showCountry", function ($compile) {
var linkFunction = function (scope, element, attributes) {
var testingVariable = scope.testingVariable;
if (testingVariable) {
switch (testingVariable.toLowerCase()) {
case "A":
// Do nothing, keep the div visible.
break;
default:
// Hide the entire div.
attributes.$set("ngIf", false);
compile(element)(scope);
break;
}
}
};
return {
restrict: "A",
link: linkFunction
};
});
<!-- My HTML with required field using my directive -->
<div class="form-group" show-country>
<label class="col-lg-6 col-md-6 control-label">
Country
</label>
<div class="col-lg-6 col-md-6">
<input name="country" type="text" placeholder="Country" ng-model="country" ng-required="true"/>
</div>
</div>
谢谢大家。
最佳答案
获取范围变量验证
并使其在条件中为假,
if (testingVariable.toLowerCase()) {
switch (testingVariable.toLowerCase()) {
case "A":
// Do nothing, keep the div visible.
break;
default:
// Hide the entire div.
scope.validate = false;
attributes.$set("ngIf", false);
$compile(element)(scope);
break;
}
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="test">
<form name="myForm">
The country input is hided and animation wil not occur
<div class="form-group" show-country validate="validate">
<label class="col-lg-6 col-md-6 control-label">
Country
</label>
<div class="col-lg-6 col-md-6">
<input name="country" type="text" placeholder="Country" ng-model="country" ng-required="true" ng-if="validate"/>
</div>
</div>
</form>
<h1>{{myForm.country.$error}}
<script>
var app = angular.module("myApp", []);
app.directive("showCountry", function ($compile) {
var linkFunction = function (scope, element, attributes) {
var testingVariable = scope.testingVariable;
console.log(testingVariable.toLowerCase())
if (testingVariable.toLowerCase()) {
switch (testingVariable.toLowerCase()) {
case "A":
// Do nothing, keep the div visible.
break;
default:
// Hide the entire div.
scope.validate = false;
attributes.$set("ngIf", false);
$compile(element)(scope);
break;
}
}
};
return {
restrict: "A",
link: linkFunction
};
});
app.controller("test", function ($scope) {
$scope.testingVariable = 'false';
});
</script>
</body>
</html>
关于javascript - 使用自定义指令在表单必填字段上动态设置 ngIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43976533/