javascript - 基于使用 ng-bind-html 添加的字段禁用提交按钮

标签 javascript html 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> 

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.$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>

选择可能是这样的 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-pristineng-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。已被实例化。

您的情况有几种解决方案:

  • 使用自定义指令绑定(bind)和编译 html - 如 this one

  • 使用 ngInclude编译 html

  • 使用 $compile编译新添加的 HTML,但这有点棘手,因为您不知道何时执行此操作

关于javascript - 基于使用 ng-bind-html 添加的字段禁用提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35920950/

相关文章:

php - 使用 Javascript 作为 php 变量返回

javascript - 检查 JavaScript 对象是否存在 null 微妙之处

javascript - 如何在单击时调用不同 div 中的 div 中的数据?

javascript - 如何对 2 个不同的 html 页面使用相同的 ng-app?

javascript - 如何在文本区域中换行?

javascript - 如何等待多个 promise ?

javascript - 调整窗口大小时如何阻止 HTML 元素被覆盖?

html - 具有内联样式的 CSS 伪类

asp.net - 如何在 html 或 asp.net aspx 文件中跳过/插入一半的行高?

javascript - 使用tinymce angular2在textarea内书写时光标跳到顶部