Angular: Passing Object to Directive, Default Attributes

http://angularjs.org/

by ramandv

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
    <pass-object title="PASS EXISTING OBJECT 1" obj="controllerObj1"></pass-object>
    <pass-object title="PASS EXISTING OBJECT 2" obj="controllerObj2"></pass-object>
    <pass-object obj="controllerObj3"></pass-object>
    <pass-object></pass-object>
    {{controllerObj}}
</div>

JavaScript

angular.module('myApp',[])

.directive('passObject', function()
    {
        return {
            restrict: 'E',
            scope: {title: '@', getObj: '&obj'},
            template: '<div>{{title}}: Hello, {{obj.prop}}!</div>',
            link: function(scope, element, attrs, controller)
            {
                if (!attrs.title)
                    attrs.title = 'DEFAULT TITLE';
                
                scope.obj = {};
                angular.extend(scope.obj, {prop: 'default prop'}, scope.getObj());                
            }                 
        };
    })

.controller('MyCtrl', function ($scope)
    {
        $scope.controllerObj1 = {prop: 'world #1'};
        $scope.controllerObj2 = {prop: 'world #2'};
        $scope.controllerObj3 = {prop: 'world #3'};
    });