Angular: button-group + highlight-changes

http://angularjs.org/

by marco_m_alves

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div ng-controller="MyCtrl">
  
  <br>
    
  <button-group
    states="modes" 
    state="mode"
    on-state-change="onModeChange">
  </button-group>

  <br>
    
  <span highlight-changes value="mode"></span>
  
  <br><br><br>
    
  <button-group
    states="periods" 
    state="period"
    on-state-change="onPeriodChange">
  </button-group>
    
  <br>
    
  <span highlight-changes value="period"></span>
    
</div>

JavaScript

var myApp = angular.module('myApp',[]);

myApp.directive('buttonGroup', function(){
  return {
    restrict: 'E',
    scope: {
      states: '=',
      state: '=',
      onStateChange: '='
    },
    template: '<div class="btn-group">' +
                '<button class="btn" ng-repeat="s in states" ng-click="select(s, $event)">' +
                    '{{s}}' + 
                '</button>' +
            '</div>',
    replace: true,
      link: function postLink(scope, elm, attrs, ctrl) {
                console.log($(elm).find('.btn'));              
          // Make sure that style is applied to initial state value
        scope.$watch(function () {
            return $(elm).find('.btn').length; // it checks if the buttons are added to the DOM
        }, function (newVal) {
            // it applies the selected style to the currently defined state, if any
            if (newVal > 0) {
                $(elm).find('.btn').each(function(index, _elm){
                    if ($(_elm).text() == scope.state) $(_elm).addClass('btn-primary');
                });
            }
        }, true);

        // Apply style changes according to selection
        scope.select = function(s, evt){  
            scope.state = s;

            $(elm).find('.btn').removeClass('btn-primary'); // reset styles on all buttons
            angular.element(evt.srcElement).addClass('btn-primary'); // apply style only to selected button
        };


        // Execute callback if it was provided
        scope.$watch('state', function(){
            if (scope.onStateChange){
              scope.onStateChange();
            }
        }, true)
      }
  };   
        
});

myApp.directive('highlightChanges', function(){
  return {
    scope: {
      value: '='
    },
    link: function(scope, elm, attrs, ctrl) {
      scope.$watch('value', function(){
        var bgColor = $(elm).css('backgroundColor');
        $(elm).text(scope.value);
        $(elm).css('backgroundColor', 'orange');
       ...