【问题标题】:angular material doesn't show error message when add attribute dinamically动态添加属性时,角度材质不显示错误消息
【发布时间】:2017-03-08 15:48:08
【问题描述】:

我的指令动态地添加了一些属性。其中一个属性是“必需的”。

angular.module('MyApp',['ngMaterial', 'ngMessages'])
    .controller('AppCtrl', function($scope) {})
    .directive("stPattern", ['$compile', stPattern]);

function stPattern($compile) {
    return {
        restrict: 'A',
        link: function ($scope, element, attrs, ngModel) {
            $timeout(function() {
                element
                    .attr("ng-pattern", /^123$/)
                    .attr("required", "required");

                element.removeAttr("st-pattern"); //because compile loop

                $compile(element)($scope);
            }, 2000);
        }
    };
}

在我看来,我创建了一个带有错误消息输入的表单:

<form name="findForm">
    <md-input-container>
        <label>CA ID</label>
        <input type="text" name="findByCaId"
               ng-model="findByCaId"
               ng-focus="$event.target.select()"
               st-pattern="">

        <div ng-messages="findForm.findByCaId.$error">
            <div ng-message="required">Campo obrigatório.</div>
            <div ng-message="pattern">Valor inválido para o campo CA ID.</div>
        </div>
    </md-input-container>
</form>

当我运行应用程序时,验证正常,但消息不显示! 当我使用 devtools 检查浏览器上的渲染代码时,我可以看到消息 div 已创建良好。

我注意到当消息出现时,一些 CSS 属性被应用于消息:

style="opacity: 1; margin-top: 0px;"

我注意到的另一件事是标签上应该有的星号。

这种行为是正确的吗?是bug吗?

###UPDATE###

我添加了 $ 超时以使代码与我的问题场景相似。

I create a fiddle to example.

谢谢!

【问题讨论】:

  • 你能创建一个 plnkr 或小提琴吗?
  • 星号是必填字段,要显示它,只需在您的input 上添加属性required。
  • 您是否将ngMessages 添加到您的角度模块中?
  • @LuizRossi,是的,我正在导入

标签: angularjs angular-material


【解决方案1】:

更改form 的子节点后,您必须重新编译form 指令,而不是那个元素。

所以不要使用$compile(element)($scope);,而是使用$compile(element[0].form)($scope);

这里是工作代码笔:http://codepen.io/anon/pen/XMMbGj?editors=1010

【讨论】:

  • 伟大的帕特里克!这对我有用!谢谢!我只是觉得有趣的是,现在具有 required 属性的字段显示了两次错误消息...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 2015-04-20
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
相关资源
最近更新 更多