var app = angular.module('plunker', []);
app.run(function($rootScope) {
// https://coderwall.com/p/ngisma
$rootScope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
})
app.directive('radioGroup', function() {
return {
restrict: 'E',
replace: true,
require: 'ngModel',
transclude: true,
template: '<ul ng-transclude></ul>',
controller: function($element, $attrs, $rootScope) {
var ngModelCtrl = $element.controller('ngModel');
var radios = [];
var select;
this.name = $attrs.name;
this.addRadio = function(scope) {
radios.push(scope);
};
select = this.select = function(value) {
console.log(value);
radios.some(function(r) {
if (r.ngValue === value) {
r.$input.attr('checked', 'checked');
return true;
}
});
ngModelCtrl.$setViewValue(value);
$rootScope.safeApply();
};
ngModelCtrl.$render = function() {
select(ngModelCtrl.$viewValue);
};
}
};
});
app.directive('radio', function($parse) {
return {
restrict: 'E',
replace: true,
require: '^radioGroup',
scope: {
ngValue: '=',
value: '@'
},
transclude: true,
template:
'<li>' +
'<input name="{{name}}" type="radio" id="radio-{{$id}}">' +
'<label for="radio-{{$id}}" ng-transclude></label>' +
'</li>',
link: function($scope, $element, $attrs, radioGroupCtrl, $transclude) {
var ngClick = $attrs.ngClick && $parse($attrs.ngClick);
$scope.name = radioGroupCtrl.name;
$scope.$input = $element.find('input');
radioGroupCtrl.addRadio($scope);
$scope.$input.on('click', function(e) {
radioGroupCtrl.select($scope.ngValue);
ngClick && ngClick($scope.$parent.$parent);
return false;
});
}
};
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-init="count = 1; fruit = 'apple'">
<radio-group name="fruit" ng-model="fruit">
<radio ng-value="'apple'">apple</radio>
<radio ng-value="'banana'" ng-click="count = count + 1">banana</radio>
</radio-group>
<div>fruit: {{fruit}} {{count}}</div>
<radio-group name="browser" ng-model="browser">
<radio ng-value="browser" ng-repeat="browser in ['Chrome', 'Firefox', 'IE', 'Safari', 'Opera']">
{{browser}}
</radio>
</radio-group>
<div>browser: {{browser}}</div>
</body>
</html>
/* Put your css in here */