title: Bootstrap "buttons-radio" toggle with AngularJS
body: <p>I made a small angular module to integrate with the bootstrap "buttons-group" ('s plus a bit of javascript to make them work like radio buttons.  I made it on this module to do the same for checkboxes: <a href="http://jsfiddle.net/evaneus/z9rge/" rel="noreferrer">http://jsfiddle.net/evaneus/z9rge/</a></p>
  
  <p>My code is at <a href="http://jsfiddle.net/askbjoernhansen/YjMMD/" rel="noreferrer">http://jsfiddle.net/askbjoernhansen/YjMMD/</a></p>
  
  <p>My questions:</p>
  
  <p>1) Is this the right approach?</p>
  
  <p>2) Will the model be watched three times, or does $scope.$watch() figure out that it's the same model and just do it once? It seems that way.</p>
  
  <p>3) Is it "correct" to muck around with the DOM in the $watch function like I do? It feels "dirty", but I guess that's what I am asking for when I am adding angular to something that's not angularjs compatible natively. Or?</p>
  
  <p>4) Is there a way to put the ng-model attribute on the btn-group instead of on each button? That'd make it appear a lot cleaner.</p>
  
  <p>You can see it at my jsfiddle above, or the code is here, first the html:</p>
  
  <pre><code> &lt;!-- to test the two-way model --&gt;
    &lt;input name="test" type="radio" ng-model="myModel['A']" value="left"&gt; Left&lt;br&gt;
    &lt;input name="test" type="radio" ng-model="myModel['A']" value="middle"&gt; Middle&lt;br&gt;
    &lt;input name="test" type="radio" ng-model="myModel['A']" value="right"&gt; Right&lt;br&gt;
  
  
  myModel A {{myModel['A']}}&lt;br/&gt;
  
  &lt;div class="btn-group" data-toggle="buttons-radio"&gt;
    &lt;button type="button" buttons-radio=""
      ng-model="myModel['A']" value="left"   class="btn"&gt;Left&lt;/button&gt;
    &lt;button type="button" buttons-radio=""
      ng-model="myModel['A']" value="middle" class="btn"&gt;Middle&lt;/button&gt;
    &lt;button type="button" buttons-radio=""
      ng-model="myModel['A']" value="right"  class="btn"&gt;Right&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>And the javascript:</p>
  
  <pre><code>angular.module('buttonsRadio', []).directive('buttonsRadio', function() {
      return {
          restrict: 'A',
          require: 'ngModel',
          link: function($scope, element, attr, ctrl) {
              element.bind('click', function() {
                  $scope.$apply(function(scope) {
                      ctrl.$setViewValue(attr.value);
                  });
              });
  
              // This should just be added once, but is added for each radio input now?
              $scope.$watch(attr.ngModel, function(newValue, oldValue) {
                  element.parent(".btn-group").find('button').removeClass("active");
                  element.parent(".btn-group")
                  .find("button[value='" + newValue + "']").addClass('active');
              });
          }
      };
  });​
  </code></pre>