title: How can I pass option changes to Angular-UI ui-select2?
body: <p>angular-ui's <a href="https://github.com/angular-ui/ui-select2" rel="nofollow noreferrer">ui-select2 documentation</a> shows that you can do something like the following:</p>
  
  <pre class="lang-js prettyprint-override"><code>myAppModule.controller('MyController', function($scope) {
      $scope.select2Options = {
          allowClear:true
      };
  });
  </code></pre>
  
  <pre class="lang-html prettyprint-override"><code>&lt;select ui-select2="select2Options" ng-model="select2"&gt;
      &lt;option value="one"&gt;First&lt;/option&gt;
      &lt;option value="two"&gt;Second&lt;/option&gt;
      &lt;option value="three"&gt;Third&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>However, changes to $scope.select2Options after that point do nothing. It would be nice if ui-select2 would watch select2Options for changes in that case and send them to select2 when they change.</p>
  
  <p>I need to dynamically change maximumSelectionSize depending on what's selected, and doing something like the following is obviously the wrong thing to do since you shouldn't be messing with the DOM in a controller.</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;select id="mySelect2" ui-select2="{ allowClear: true}" ng-model="select2" ng-change="selectChange()"&gt;
      &lt;option value="one"&gt;First&lt;/option&gt;
      &lt;option value="two"&gt;Second&lt;/option&gt;
      &lt;option value="three"&gt;Third&lt;/option&gt;
  &lt;/select&gt;
  </code></pre>
  
  <p>inside controller:</p>
  
  <pre class="lang-js prettyprint-override"><code>$scope.selectChange = function() {
      if(...) {
          $("#mySelect2").select2({ maximumSelectionSize: 1 });
      } else {
          $("#mySelect2").select2({ maximumSelectionSize: 0 });
      }
  }
  </code></pre>
  
  <p>How can I pass those types of options through to select2 without using the DOM and mixing concerns in my controller? (I couldn't come up with a clean way to do this via a directive.)</p>
  
  <p>Thanks!</p>
  
  <p><strong>Update:</strong></p>
  
  <p>Based on <a href="https://stackoverflow.com/a/16962249/405026">https://stackoverflow.com/a/16962249/405026</a>, Stewie's answer, and my own testing I've added the following code to angular-ui ui-select's link method:</p>
  
  <pre class="lang-js prettyprint-override"><code>try {
      scope.uiSelect2 = angular.fromJson(attrs.uiSelect2);
  } catch(e) {
      scope.$watch(attrs.uiSelect2, function (opts) {
          if (!opts) return;
          elm.select2(opts);
      }, true);
  }
  </code></pre>
  
  <p>Is there a better way of handling the case where the ui-select2 attribute may be either an object literal or an object on the scope?</p>