在Angularjs中将整个表单设为只读 [英] Make the whole form as readonly in Angularjs
问题描述
在我的Anuglarjs 1.5应用程序中,我有很多带有表单的页面。
In my Anuglarjs 1.5 application I have a lot of pages with a form in them.
我想采用某种机制来禁用某些表格,当我谷歌搜索它,我发现用字段集封装表单元素并使其禁用将成功。当我测试它工作,但只有输入和按钮被禁用,而不是可点击的元素,如(divs,span,icon ...)。
I wanted to adopt some mechanism to make some forms disabled, and when I googled about it, I found that encapsulating the form element with a fieldset and make it disabled will do the trick. when I test it it worked, but only inputs and buttons were disabled and not clickable elements like (divs, spans, icons...).
所以我决定是,创建一些函数,将添加一个字段集,并在我满足条件时将其设置为禁用,使我的表单元素只读,但我不知道如何访问表单direcive所以我可以创建一个post link函数执行该功能。
So what I decided to do, is to create some function that will add a fieldset and set it disabled whenever I met the condition to make my form elements readonly, but I don't know how can I access to the form direcive so I can create a post link function to execute that function.
我该怎样解决这个问题?
How can I solve this ?
推荐答案
您不能使整个表单只读或禁用。您需要单独输入或禁用单个输入。
You can't make the whole form readonly or disabled. You need to make individual inputs readonly or disabled.
您可以使用表单元素并使用 ng-readonly attribute 或 ng-disabled
You can use a form element and use ng-readonly attribute or ng-disabled
这是一个工作示例
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="formCtrl">
<form>
Name: <input type="text" ng-model="firstname">
<br/>
<br/>
Disabled Name: <input type="text" ng-model="firstname" ng-disabled="true">
<br/>
<br/>
Readonly Name: <input type="text" ng-model="firstname" ng-readonly="true">
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>
</body>
</html>
更新
如果您无法使用上述方法并想要停用所有表单,那么您可以使用以下代码。 您可以将已禁用属性替换为只读。
If you can't use the above method and want to disable every form, then you could use the below code. You can replace the "disabled" attribute with "readonly".
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="formCtrl">
<form name="form1">
First Name: <input type="text" ng-model="firstname">
<br/>
First Name: <input type="text" ng-model="firstname">
<br/>
First Name: <input type="text" ng-model="firstname">
<br/>
</form>
<form name="form2">
<input type="text" ng-model="firstname">
<textarea type="text" ng-model="firstname">
</textarea>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
angular.forEach(document.forms,(f)=>{
angular.forEach(f.children,(i)=>{
i.setAttribute("disabled", "disabled");
});
});
});
</script>
</body>
</html>
这篇关于在Angularjs中将整个表单设为只读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!