Angular: Passing Object to Directive, Default Attributes

http://angularjs.org/

by joshdmiller

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 obj="controllerObj4"></pass-object>
</div>

JavaScript

angular.module('myApp',[])

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

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