Transclusion Example

by Michael Hunziker

HTML

<script src="https://code.angularjs.org/1.3.1/angular.js"></script>
<body ng-app="transcludeExample">
    <div ng-controller="ExampleController">
        <task-list tasks="tasks">
            <ul ng-repeat="task in tasks track by $index">
                <li>{{task.title}}</li>
            </ul>
        </task-list>
    </div>
</body>

JavaScript

angular.module('transcludeExample', [])
    .directive('taskList', function () {
    return {
        restrict: 'E',
        transclude: true,
        scope: {
            tasks: '='
        },
        controller: function ($scope) {
            $scope.addTask = function () {
                if (!$scope.tasks) $scope.tasks = [];
                $scope.tasks.push({
                    title: $scope.title
                });
            };
        },
        template: '<div>' +
            '   Name: <input type="text" ng-model="title" />' +
            '   <button ng-click="addTask()">Add Task</button>' +
            '   <div class="container"><br />' +
            '      <ng-transclude></ng-transclude>' +
            '   </div>' +
            '</div>'
    };
})
    .controller('ExampleController', ['$scope', function ($scope) {
    $scope.tasks = [{
        title: 'ToDo1'
    }, {
        title: 'ToDo2'
    }];
}]);