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">
    <h6>Data source in the controller</h6>
    options={{options}}
    <br><br>
    <h6>Rendered directive that uses "&amp;"</h6>
    {{comment}}
    <br><br>
    <test options="options" describe="describe"></test>
   
        
</div>

JavaScript

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

myApp.directive('test', function() {
    return {
        restrict: 'E',
        template: '<div ng-repeat="option in options">{{describe()(option)}}<div>',
        scope: {
            options: "=",
            describe: "&"
        }
    };
});

myApp.controller("MainCtrl", function($scope) {
    
    $scope.log = [];

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

    $scope.describe = function(option){
        if (option) {
            var d = option.id + ": " + option.name;
            return d;
        } else {
            return "unknown";
        }
    };
    
    $scope.comment = 'The content of each line is the result of calling the controller describe method by using "{{describe()(option)}}" inside the directive template. Notice the "first call" with just () and no args, and the "second call" with the argument.';

});