title: How do I dynamically add a ng-pattern attribute to an html element?
body: <p>I have a multi-purpose modal dialog in my app with one text input.
  Sometimes I need just any text, sometimes I want to restrict the text to match a regex pattern.</p>
  
  <p>I tried adding the regex with jQuery <code>attr</code> like this:</p>
  
  <pre><code>$("#popupTextInput").attr("ng-pattern", "/.*imdb\.com\/title\/.*/");
  </code></pre>
  
  <p>Doesn't work. When I inspect the rendered element the correct <code>ng-pattern</code> directive appears on the element but the <code>formname.$valid</code> is always true, no matter what I enter.</p>
  
  <p>When I manually add the attribute (with the exact same appearance in firebug) it works as expected.</p>
  
  <p>Instead of a string with the pattern I also tried adding a regex pattern directly to the attribute like this:</p>
  
  <pre><code>var regexp = /.*imdb\.com\/title\/.*/;
  $("#popupTextInput").attr("ng-pattern", regexp);
  </code></pre>
  
  <p>But that doesn't work either.</p>
  
  <p>I am puzzled. Can anybody shed some light on this?
  I should probably mention that I add the attribute <strong>before</strong> I create the modal.</p>
  
  <p>ETA:
  Did some further experiments. I tried having ng-pattern on the input by default and remove when not needed.
  Something similar happened:
  When I remove the ng-pattern it is removed from the element (at least inspection doesn't show it) but the regex pattern is still in effect.
  I tried the $scope.$apply suggestion below (with and without function in $apply) but it has no effect.</p>