JSFiddle 在这里:http://jsfiddle.net/c6tzj6Lf/4/
我正在动态创建表单和按钮,如果未完成所需的表单输入,我想禁用这些按钮。
HTML:
<div ng-app="choicesApp">
<ng-form name="choicesForm" ng-controller="ChoicesCtrl">
<div ng-bind-html="trustCustom()"></div>
<button ng-repeat="button in buttons" ng-disabled="choicesForm.$invalid">
{{button.text}}
</button>
</ng-form>
</div>
JavaScript:
angular.module('choicesApp', ['ngSanitize'])
.controller('ChoicesCtrl', ['$scope', '$sce', function($scope, $sce) {
$scope.custom = "Required Input: <input required type='text'>";
$scope.trustCustom = function() {
return $sce.trustAsHtml($scope.custom);
};
$scope.buttons = [
{text:'Submit 1'},
{text:'Submit 2'}];
}]);
choicesForm.$invalid
为 false
并且在输入字段中输入文本时不会更改。
解决方案:
我最终使用了此处的 angular-bind-html-compile 指令:https://github.com/incuna/angular-bind-html-compile
这里是相关的工作代码:
<ng-form name="choicesForm">
<div ng-if="choices" bind-html-compile="choices"></div>
<button ng-click="submitForm()" ng-disabled="choicesForm.$invalid">
Submit
</button>
</ng-form>
选择可能是这样的 HTML 片段:
<div><strong>What is your sex?</strong></div>
<div>
<input type="radio" name="gender" ng-model="gender" value="female" required>
<label for="female"> Female</label><br>
<input type="radio" name="gender" ng-model="gender" value="male" required>
<label for="male"> Male</label>
</div>
最佳答案
主要问题是 ngBindHtml不编译 html - 它按原样插入 html。您甚至可以检查动态输入并发现它没有 ngModel's CSS classes ( ng-pristine
、 ng-untouched
等)这是一个主要的危险信号。
在您的情况下,表单根本不知道您已经添加了另一个输入或与此相关的任何更改。它的状态($pristine、$valid 等)不是由它的 HTML 决定的,而是由注册的 NgModelControllers 决定的。 . ngModel 时会自动添加这些 Controller 已链接。
- 例如这个
<input required type='text'>
不会影响表单的有效性,即使它是必需的,因为它没有分配给它的 ngModel。 - 但是这个
<div ng-model="myDiv" required></div>
会影响它,因为它是必需的并且已为其分配了 ngModel。
ngDisabled按钮上的指令按预期工作,因为它取决于 form's $invalid property .
查看此 fiddle它展示了 ngModel 如何注册其 Controller 。请注意,包含动态输入的 html 在 750 毫秒后被编译,只是为了展示如何在 FormController 之后添加 NgModelControllers。已被实例化。
您的情况有几种解决方案:
关于javascript - 基于使用 ng-bind-html 添加的字段禁用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920950/