2017-03-08 61 views
0

我的指令可以添加一些属性。其中一个属性是“必需的”。角度材质在添加属性时不会显示错误信息

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;" 

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

该行为是否正确?是一个错误?

### UPDATE ###

我增加了$超时保持类似我的问题情景的代码。

I create a fiddle to example.

谢谢!

+0

你可以创建一个plnkr或摆弄? – lin

+0

星号用于必填字段,只需在'input'中添加'required'属性即可。 –

+0

您是否已将ngMessages添加到您的角度模块? –

回答

1

在对form的子节点进行更改之后,您必须重新编译form指令,而不是该元素。

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

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

+0

这是伟大的Patryk!这对我有用!谢谢! 我只是觉得很有趣,现在具有所需属性的字段显示错误消息两次... –