twitter bootstrap form-group 的 AngularJS 指令

2023-12-30

我最近一直在玩 Angular,到目前为止一切都很好,但我在指令方面遇到了困难。

我正在尝试创建一个指令,为标准引导表单组生成 html 标记及其相应的验证消息。

所以基本上我正在尝试转换它:

<form-group label="Password">
        <input type="password" data-ng-model="vm.password" name="password" id="password" class="form-control form-control-validate"
               required data-ng-minlength="6"
               data-required-error="Password is required" data-minlength-error="Your password must have at least 6 characters" />
</form-group>

进入这个:

<div class="form-group" data-ng-class="{'has-error': invalid}">
        <label for="password" class="col-md-2 control-label">Password</label>
        <div class="col-md-10">
            <input data-ng-model="vm.password" type="password" id="password" name="password" class="form-control"
                   required data-ng-minlength="6"/>
            <div data-ng-show="changePasswordForm.$dirty && changePasswordForm.oldPassword.$invalid">
                <label data-ng-show="changePasswordForm.oldPassword.$error.required" class="label label-danger">
                    Password is required
                    <br />
                </label>
                <label data-ng-show="changePasswordForm.oldPassword.$error.minlength" class="label label-danger">
                    Your password must have at least 6 characters
                </label>
            </div>
        </div>
</div>

到目前为止,这就是我所拥有的:

app.directive('formGroup', function () {
    return {
        templateUrl: 'app/directives/formGroup.html',
        restrict: 'E',
        replace: true,
        transclude: true,
        require: "^form",
        scope: {
            label: "@",
        },
        link: function (scope, element, attrs, formController) {
            var input = element.find(":input");
            var id = input.attr("id");
            scope.for = id;
            var inputName = input.attr("name");
            // Build the scope expression that contains the validation status.
            // e.g. "form.example.$invalid"
            var inputInvalid = [formController.$name, inputName, "$invalid"].join(".");
            scope.$parent.$watch(inputInvalid, function (invalid) {
                scope.invalid = invalid;
            });
        }
    };
});

表单组.html:

<div class="form-group" ng-class="{ 'has-error': invalid }">
   <label class="col-md-2 control-label" for="{{for}}">{{label}}</label>
   <div class="col-md-10">
      <div data-ng-transclude=""></div>
   </div>
</div>

如果输入无效,这会将引导类“has-error”正确设置为表单组。

现在我想添加验证消息,但找不到可行的方法。这就是我所拥有的:

app.directive('formControlValidate', function () {
    return {
        templateUrl: "app/directives/formControlValidate.html",
        restrict: 'C',
        require: ["^form", "ngModel"],
        scope: { },
        transclude: true,
        //replace: true,
        link: function (scope, element, attrs, controls) {
            var form = controls[0];
            var inputName = attrs.name;
            var inputErrors = [form.$name, inputName, "$error"].join(".");
            scope.$parent.$watch(inputErrors, function (newValue) {
                if (newValue) {
                    scope.errors = [];
                    angular.forEach(newValue, function (value, key) {
                        var error = attrs[key + 'Error'];
                        if (value && error) {
                            scope.errors.push(error);
                        }
                    });
                }
            }, true);
        }
    };

表单控件Validate.html:

<div class="controls" ng-transclude></div>
    <div data-ng-repeat="error in errors">
    <div class="label label-danger">
        {{error}}
    </div>
</div>

但这行不通。我随机更改两个指令中的参数,但不知道如何使其工作。

任何想法或改进将不胜感激。

Thanks!


UPDATE:这是我的最新要点(角度1.3):https://gist.github.com/lpsBetty/3259e966947809465cbe https://gist.github.com/lpsBetty/3259e966947809465cbe


旧解决方案:

我尝试过类似的方法,也许这个链接也可以帮助你:http://kazimanzurrashid.com/posts/create-angularjs-directives-to-remove-duplicate-codes-in-form http://kazimanzurrashid.com/posts/create-angularjs-directives-to-remove-duplicate-codes-in-form

这是我的解决方案。我不知道为什么,但我必须使用 form.$dirty,不可能使用 input.$dirty.. (我使用角度翻译)

HTML:

<form-group input="form.password">
  <input type="password" class="form-control" placeholder="{{ 'user.password' | translate }}" required
          name="password" ng-model="user.password" />
</form-group>

指示:

  app.directive('formGroup', function ($parse) {
    return {
      restrict: 'E',
      require: '^form', 
      transclude: true,
      replace: true,
      scope: {
        cssClass: '@class',
        input: '='
      },
      template: '<div class="form-group" ng-class="{\'has-error\':hasError, cssClass:true}">'+
                  '<div ng-transclude></div>' +
                  '<div ng-show="hasError">' +
                    '<span ng-repeat="(key,error) in input.$error" class="help-block"' +
                            'ng-show="input.$error[key]">{{\'form.invalid.\'+key | translate}}</span>' +
                  '</div>' +
                '</div>',
      link: function (scope, element, attrs, ctrl) {
        var form = ctrl;
        var input = attrs.input;

        scope.$parent.$watch(input+'.$invalid', function (hasError) {
          scope.hasError = hasError && form.$dirty;
        });
      }
    };
  });
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

twitter bootstrap form-group 的 AngularJS 指令 的相关文章

随机推荐

  • 使用 moment.js 获取该月的第一个工作日

    我有一些代码使用 moment js 这是一个要求 获取该月的第一个工作日 如下所示 dateStart function var first moment startOf month switch first day case 6 ret
  • 如何将 /etc/resolv.conf 下的自定义名称服务器添加到 pod 中?

    哪个服务在 pod 的 etc resolv conf 下分配名称服务器 通常应该从主机 etc resolv conf 获取 我在 pod 的 etc resolv conf 下看到不同的名称服务器 kbernetes 上是否有任何配置
  • Pandas / xlsxwriter writer.close() 没有完全关闭excel文件

    我试图在使用 python 脚本创建 Excel 文件后手动修改它 不幸的是 如果脚本仍在运行 则在尝试使用相同名称保存脚本时会出现共享文件冲突错误消息 代码中一切都运行顺利 文件已创建 填充并保存 我可以打开它并对其进行处理 但如果脚本仍
  • symfony 5.1 捆绑迁移导致没有要处理的映射信息

    我正在 DDD 下开发 Symfony 5 1 项目 因此我对所有默认文件夹进行了一些更改 我在 src 文件夹中有 2 个包 目前我只在其中一个包中有实体 我使用命令 make user 生成了实体用户及其存储库 然后移动文件并更改命名空
  • VBA 高度持久的运行时错误 91

    我遇到的问题是 当我尝试启动宏时 我不断收到错误 代码是 Sub MAGAZINE iiii Dim IE As InternetExplorer MODIFICATION Dim els el colDocLinks As New Col
  • 请问在函数内部使用 func() 在 python 中意味着什么

    请问在函数内部使用 func 在 python 中意味着什么 例如下面的代码 def identity decorator func def wrapper func return wrapper func是赋予函数的参数identity
  • Safari 移动设备忽略阻止默认设置

    我在用e preventdefault 在谷歌地图信息窗口中的链接上 它在桌面上按预期工作 其中链接不访问href但在 Safari 上 它似乎会忽略它并访问该链接 就好像没有加载 JavaScript 一样 它显然正在加载 JavaScr
  • “对象处于不一致状态”的含义

    我曾多次遇到过 以特定方式对对象进行编码可能会导致其处于不一致的状态 一个例子是这样的question https stackoverflow com questions 4768349 builder vs decorator patte
  • 云技术的最佳概述是什么? [关闭]

    Closed 此问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 围绕云技术有很多讨论 您会推荐哪些资源来回顾云计算世界并帮助人们了解大局 and 当前的趋势 除了阅读这
  • 具有尾随返回类型的模板成员函数,即使未使用也会出错

    据我所知 模板成员函数仅在使用时才会生成 如果不是所有使用的类型都支持这样的功能 这很方便 但是 这似乎不适用于具有尾随返回类型规范的函数 下面是一个小实验 helper function for case A workaround tem
  • 如何显示未促销的 WooCommerce 产品?

    我想展示非销售产品仅意味着常规产品 排除销售产品 在 WooCommerce 中 我的页面仅显示常规产品 那么谁能告诉我该怎么做 我设法过滤掉没有销售的产品 并将下面的代码放置在if have posts args array post t
  • phpMyAdmin - 错误:关系功能被禁用

    当我想使用 phpMyAdmin 4 3 8 在设计器模式下创建两个表之间的关系时 它给我一个错误 错误 关系功能已禁用 当我尝试使用 4 1 4 时 它工作得很好 我似乎找不到应该在哪里更改设置才能在设计器模式下创建关系 任何想法 提前致
  • Paperclip S3 下载远程图像

    如何下载远程图像 http协议 url位于image remote url属性中 并通过Paperclip将其保存为S3的附件 class Product lt ActiveRecord Base require open uri attr
  • 在固定时间后中断线程,是否必须抛出InterruptedException?

    我想在固定时间后中断线程 其他人问了同样的问题 投票最高的答案 https stackoverflow com a 2275596 1310503 https stackoverflow com a 2275596 1310503 给出了下
  • 在 MacOSX (Macbook Pros) 上以编程方式读取 CPU 温度(+其他传感器数据)

    我想以编程方式从我的 MacBook Pro 2009 型号 读取 CPU 温度和任何其他有趣的传感器数据 我该怎么做 我注意到一个上一篇文章 https stackoverflow com questions 2216888 how to
  • 在 Spring 中格式化/缩进 JaxB 编组器

    我正在尝试对 Spring 中的 Jaxb2Marshaller 类的输出 XML 进行 PrettyPrint 缩进 格式化 即使我输入的属性如 Web 上其他地方所见 该文件仍然全部在一行上 这是我的 bean 声明
  • C++:我想在所有 CPP 文件之间使用这个配置类,如何初始化它?

    class Config public static int OUTPUT TO FILE static int NEED TO TRAIN static int NO FILE TRAIN static int NEED TO TEST
  • Java 创建临时文件

    名称的最大长度是多少TempFile在java中和MaximumFilesize取决于 在我们提到要创建的临时目录或其他基于java的机器上 何时致电deleteOnExit 方法 但是这个方法有什么用 因为它会在 JVM 关闭时被调用 但
  • Glide - 下载 GIF 并调整其大小到文件中

    我需要下载一个 GIF 并将其保存到外部存储 以便我可以通过彩信发送它 消息的大小限制为 300kb 并且大多数 GIF 太大 因此我需要调整它们的大小 我在项目的其余部分中使用 Glide Glide 有一个漂亮的功能 理论上应该下载调整
  • twitter bootstrap form-group 的 AngularJS 指令

    我最近一直在玩 Angular 到目前为止一切都很好 但我在指令方面遇到了困难 我正在尝试创建一个指令 为标准引导表单组生成 html 标记及其相应的验证消息 所以基本上我正在尝试转换它