Simple Angular Binding demo with directive

Externalize the time into a separate directive component.

by Ben Clayton

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<div ng-app='demo'>
    <h3>Greeting</h3>
    <p ng-controller='MyCtrl'>My name is <b>{{name}}</b>. 
        My Age is <display-time />.
    </p>

    <p ng-controller='MyCtrl'>
        Company <b>{{companyname}}</b><br/> 
        Town <b>{{town}}</b><br/> 
        Primary Phone <b>{{phone[0]}}</b><br/> 
    </p>
    <p ng-controller='MyCtrl'>
        Type <b>{{num.digits}}</b><br/> 
    </p>
    
    
</div>

CSS

.myclass { color:red; }

JavaScript

var demo = angular.module('demo', []);
demo.directive('displayTime', function($parse) {
    return {
        // match only Element tag name i.e. 'display-time' must be the tag name
        restrict: 'E',
        replace: true,
        transclude: false,
        // template can only be a single element
        template: '<span id="123" class="currentTime {{cls}}"></span>',
        // link means data bind ?
        link: function (scope, element, attrs, controller) {
            var currentDate = new Date();
            console.log(attrs);
            console.log(scope);
            // update content of span which has been inserted;
           element.text( new Date(currentDate - scope.myDOB ).getFullYear()-1970 );
        }
    }
});

// this is the controller which holds the data
function MyCtrl ($scope) {
    $scope.name = 'Fred';   
    $scope.myDOB = new Date('1986-01-28');  // DOB  
    $scope.companyname = 'InFX';
    $scope.town = 'Hastings';
    $scope.phone = ['01424555555','01424424955'];
    $scope.num={};
    $scope.num.digits=9;
    $scope.cls="myclass";
};