angular js directive attribute defaults

by enigment

HTML

<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyCtrl">
    <b>setting missing attrs works</b>
    <test1 a1="foo" a2="bar"></test1> 
    <test1 a1="baz"></test1>
    <test1></test1>
    <hr />
      
    <b>setting all in scope doesn't set defaults</b>
    <test2 a1="foo" a2="bar"></test2>
    <test2 a1="baz"></test2>
    <test2></test2>
    <hr />
      
    <b>setting all in attrs ignores passed attributes</b>
    <test3 a1="foo" a2="bar"></test3>
    <test3 a1="baz"></test3>
    <test3></test3>
</div>

JavaScript

angular.module('myApp', [])

.directive('test1', function ()
{
  return {
    restrict: 'E',
    scope: {a1: '@', a2: '@'},
    template: '<div>{{a1}} {{a2}}</div>',
    replace: true,
    link: function (scope, element, attrs, controller)
    {
      var attrDefaults = {a1: 'a1-default', a2: 'a2-default'}
      angular.forEach(attrDefaults, function (value, key)
      {
        if (!attrs[key])
          attrs[key] = value;
      });
    }
  };
})
.directive('test2', function ()
{
  return {
    restrict: 'E',
    scope: {a1: '@', a2: '@'},
    template: '<div>{{a1}} {{a2}}</div>',
    replace: true,
    link: function (scope, element, attrs, controller) 
    {
      scope.a1 = 'a1-default';
      scope.a2 = 'a2-default';
    }
  };
})
.directive('test3', function ()
{
  return {
    restrict: 'E',
    scope: {a1: '@', a2: '@'},
    template: '<div>{{a1}} {{a2}}</div>',
    replace: true,
    link: function (scope, element, attrs, controller) 
    {
      attrs.a1 = 'a1-default';
      attrs.a2 = 'a2-default';
    }
  };
})

.controller('MyCtrl', function ($scope)
{
});