Angular: Radio group
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<form name="tarifForm" ng-controller="Main">
<radio-group required>
<div ng-repeat="i in items">
<label>
<input type="radio" value="{{i.id}}" name="radioTest" ng-model="value" />
<span>{{i.name}}</span>
</label>
</div>
</radio-group>
<p>
$touched: {{tarifForm.radioTest.$touched}}
</p>
</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', []).controller('Main', Main);
function Main($scope) {
$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: '^form',
link: function(scope, elm, attr, ctrl) {
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.$setTouched();
});
}
});
}
};
}]);