Widgets

by ChrisP

HTML

<div ng-app="app" ng-controller="MainCtrl">
    <div class="widget">
        <h6>Widget {{ currentWidget().num }}</h6>
        <radio-group group-name="Radio Group">
        <p ng-repeat="itm in currentWidget().items">
        <radio ng-model="itm.select">
            {{ itm.title }}
        </radio>
        </p>
        </radio-group>
    </div>
    <div class="selector">
        Select a widget:
        <select ng-model="current">
          <option>0</option>
          <option>1</option>
        </select>
    </div>
    <button ng-click="next()">Next Widget</button>
    <br/>
    {{ widgets }}
</div>

CSS

.widget {
    border: 1px solid black;
    margin: 10px;
    padding: 10px;
}
.selector {
    margin: 10px;
}

JavaScript

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

app.controller('MainCtrl', function($scope) {
        $scope.widgets = [{num: 0, items: [{title:'milk',select:false},
                                           {title:'eggs',select:true}]},
                          {num: 1, items: [{title:'soup',select:false},
                                           {title:'nuts',select:false}]}
                         ];
        $scope.current = 0;
        $scope.currentWidget = function () {
             return $scope.widgets[$scope.current];   
        }
        $scope.set = function(idx, sub) {
            this.widgets[idx].items[sub].select = !this.widgets[idx].items[sub].select;
        }
        
        $scope.next = function () {
           $scope.current += 1;
            if ($scope.current >= $scope.widgets.length) {
                $scope.current = 0;
            }
        }
        $scope.isChecked = function (val) {
            if (val) {
                return 'checked';
            }
            return '';
        }
    });

app.directive('radioGroup', function () {
    return {restrict: 'EA',
            replace: true,
            transclude: true,
            scope: {name: '@groupName'},
            template: '<div><h5>{{name}}</h5><div ng-transclude></div></div>',
            controller: function ($scope, $element) {
                var radios = [];
                $scope.radios = radios;
                // return the name of this group
                this.getName = function () { return $element.attr('group-name'); }
                // add a radio item to the group
                this.addRadioItem = function (r) {
                    radios.push(r);
                }
                // cycle through and update the model when any single radio changes state
                this.select = function (chosen) {
                    angular.forEach(radios, function (r) {
                        if (chosen != r) {
                            r.ngModel = false;
               ...