title: Angularjs Custom select2 directive
body: <p>I have created simple custom AngularJs directive for this awesome jquery plugin <a href="http://select2.github.io/select2/" rel="noreferrer">jQuery-Select2</a> as follows:</p>
  
  <p><strong>Directive</strong></p>
  
  <pre><code>app.directive("select2",function($timeout,$parse){
      return {
          restrict: 'AC',
          link: function(scope, element, attrs) {
              $timeout(function() {
                  $(element).select2();
              },200); 
          }
      };
  });
  </code></pre>
  
  <p><strong>Usage in HTML templates:</strong></p>
  
  <pre><code>&lt;select class="form-control" select2 name="country"
  data-ng-model="client.primary_address.country"
  ng-options="c.name as c.name for c in client.countries"&gt;
       &lt;option value=""&gt;Select Country&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>It is working as expected and my normal <code>select</code> element is replaced by <code>select2</code> plugins. </p>
  
  <p>However there is one issue though, sometimes it is showing default value i.e <code>Select Country</code> here although in dropdown proper model value is auto selected.</p>
  
  <p>Now if I increase <code>$timeout</code> interval from <code>200</code> to some high value say <code>1500</code>, it is working but delays the the rendering of directive. Also I think this is not proper solution for it, as my data is getting loaded via ajax.</p>
  
  <p>I have also tried to update directive as follows, but no luck in that either:</p>
  
  <pre><code>app.directive("select2",function($timeout,$parse){
      return {
          restrict: 'AC',
          require: 'ngModel',
          link: function(scope, element, attrs) {
              var modelAccessor = $parse(attrs.ngModel);
              $timeout(function() {
                  $(element).select2();
              });
              scope.$watch(modelAccessor, function (val) {
                  if(val) {
                      $(element).select2("val",val);
                  }
              });
          }
      };
  });
  </code></pre>
  
  <p>PS: I know that there is similar module present <a href="https://github.com/angular-ui/ui-select" rel="noreferrer">ui-select</a>, but it requires some different markup in form of <code>&lt;ui-select&gt;&lt;/ui-select&gt;</code>, and my App is already fully developed and I just want to replace normal select box with select2.</p>
  
  <p>So can you please guide me how can I resolve this issue and make sure that directive keeps in sync with latest behaviour?</p>