2013-05-07 20 views
0

我正在创建一个输入指令,当用户输入除数字以外的任何内容时,我希望该框变为红色。我能够通过以下
为什么ng-pattern在指令内一直返回false?

<input ng-model='numberNoDir' type='text' ng-pattern='/^\d*$/'> 


解决这个,但是当我把它放在一个指令,那么它总是返回false,即使我输入一个数字。 Here is the Plunker of to reproduce the problem。我有这个编译比链接,因为它需要用新的DOM替换当前的DOM。在这里使用编译而不是链接是否正确?还有为什么指令总是返回false? 谢谢

回答

2

\ JavaScript中的字符是转义字符。它在你的HTML中工作,因为\不用于在HTML中转义任何东西。你需要在你的指令中使用\\。你可能已经知道这一点,但没有意识到这是你的问题。 :)

如果您的模板不打算使用ngTransclude指令,也不需要$编译模板或使用transclude选项。你的指示可以被固定和简化为:

app.directive("numberInput", function(){ 
    return { 
     restrict: 'E', 
     scope: { 
      fooBar: "=ngModel" 
     }, 
     require: "ngModel", 
     template: "<input type='text' ng-model='fooBar' ng-pattern='/^\\d*$/'>" 
    } 
}); 
+0

哇完全忘了\\,我一直在想我在编译器或链接中弄乱了一些东西。谢谢一吨 – Nair 2013-05-07 05:41:02