Angular: Radio group

by cambiata

HTML

<script src="http://ci.angularjs.org/job/angular.js-angular-master/lastSuccessfulBuild/artifact/build/pkg/0.10.7-e86bafec/angular-0.10.7-e86bafec.js"></script>
<form name="form">
  <radio-group ng:model="value" ng:change="change(value)" required>
    <div ng:repeat="i in items">
      <input type="radio" value="{{i.id}}" name="some" id="radio_{{i.id}}" />
      <label for="radio_{{i.id}}">{{i.name}}</label><br />
    </div>
  </radio-group>

  <a ng:click="value='1'">set to 1</a><br />
  value = {{value}} ({{items[value].name}})<br />
</form>

CSS

.ng-invalid {
    border-color: red;
}

.ng-valid {
    border-color: green;
}

.ng-dirty {
    border-style: solid;
    border-width: 2px;
}

.ng-pristine {
    border-style: solid;
    border-width: 1px;
}

.errors {
    color: red;
}

radio-group {
  display: block;
}

JavaScript

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

function Main($scope) {
  $scope.change = function(value) {
    console.log('ng:change fired', value);
  };

  $scope.items = [{
    id: 0,
    name: 'Zero',
    email: '[email protected]'
  }, {
    id: 1,
    name: 'One',
    email: '[email protected]'
  }, {
    id: 2,
    name: 'Two',
    email: '[email protected]'
  }, {
    id: 3,
    name: 'Three',
    email: '[email protected]'
  }];
}

myApp.directive('radioGroup', [function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attr, ctrl) {
      ctrl.render = function() {
        angular.forEach(elm.find('input'), function(input) {
          input.checked = input.value == ctrl.viewValue;
        });
      };

      elm.bind('click', function(event) {
        var input = event.target;

        // we can use .live() when using jq
        if (input.nodeName.toLowerCase() === 'input' && input.type === 'radio') {
          scope.$apply(function() {
            ctrl.touch();
            if (input.value != ctrl.viewValue) {
              ctrl.read(input.value);
            }
          });
        }
      });
    }
  };
}]);