Angular: Directive with "&" scope

Learning how to use the & scope

by marco_m_alves

HTML

<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://raw.github.com/documentcloud/underscore/master/underscore.js"></script>
<div ng-app="myApp" ng-controller="MainCtrl">

<switchboard entry="entry" options="options" describe="renderOption" is-present="hasOption" on-toggle="toggleOption"></switchboard>

</div>

JavaScript

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

myApp.directive('switchboard', function() {
    return {
        restrict: 'E',
        template: '<div style="vertical-align: top"><table class="worker-services-table table-bordered"><tr ng-repeat="opt in options"><td>{{describe({option: opt})}}</td><td><input type="checkbox" ng-model="optionIndex[opt]" ng-click="toggle(opt)"</td></tr></table><div>',
        scope: {
            entry: "=",
            options: "=",
            describe: "&",
            isPresent: "&",
            onToggle: "&"
        },
        controller: function($scope) {

            var optionIndex = {};

            var indexOptions = function() {
                if ($scope.options) {
                    $scope.optionIndex = {};
                    $scope.options.forEach(function(opt) {
                        $scope.optionIndex[opt] = $scope.isPresent(opt);
                    });
                }

            }

            $scope.toggle = function(c) {
                $scope.onToggle(c);
            };

            //indexOptions();
        }
    }
});

myApp.controller("MainCtrl", function($scope) {

    $scope.options = [
        {
        id: 1,
        name: "A"},
    {
        id: 2,
        name: "B"},
    {
        id: 3,
        name: "C"},
    {
        id: 4,
        name: "D"}
    ];

    $scope.entry = {
        optionIds: [2]
    };

    $scope.renderOption = function(option) {
        return option.name;
    };

    $scope.hasOption = function(option) {
        _.include($scope.entry.optionIds, option.id);
    };

    $scope.toggleOption = function(option) {
        console.log("controller toggle");
        console.log(option);
        if ($scope.hasOption()) {
            var idx = _.indexOf($scope.entry.optionIds, option.id);
            that.optionIds.splice(idx, 1);
        } else {
            $scope.entry.optionIds.push(option.id);
        }
    };

});