dis*_*rse 8 html javascript angularjs
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>
Run Code Online (Sandbox Code Playgroud)
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'}];
}]);
Run Code Online (Sandbox Code Playgroud)
choicesForm.$invalidfalse在输入字段中输入文本时是和不会改变.
解:
我最终使用了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>
Run Code Online (Sandbox Code Playgroud)
选择可能是像这样的HTML的snippit:
<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>
Run Code Online (Sandbox Code Playgroud)
主要问题是ngBindHtml没有编译html - 它按原样插入html.你甚至可以检查动态输入,并认为它不具备ngModel的CSS类(ng-pristine,ng-untouched,等),这是一个重大的红旗.
在您的情况下,表单根本不知道您已添加其他输入或任何已更改的内容.它的状态($ pristine,$ valid等)不是由它的HTML决定的,而是由注册的NgModelControllers决定的.链接ngModel时会自动添加这些控制器.
<input required type='text'>不会影响表单的有效性,即使它是必需的,因为它没有为其分配ngModel.<div ng-model="myDiv" required></div>会影响它,因为它是必需的并且已经为其分配了ngModel.按钮上的ngDisabled指令按预期工作,因为它取决于表单的$ invalid属性.
请参阅此小提示,其中展示了ngModel如何注册其控制器.请注意,包含动态输入的html在750ms之后编译,以显示在实例化FormController之后如何添加NgModelControllers .
您的案例中有一些解决方案: