AngularJS - Custom Elements ex

by gavinfoley

HTML

<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <tel>+64 21 142 0679</tel>
        <email>
            <address>[email protected]</address>
            <text>gavin</text>            
        </email>
    </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script> <style>

JavaScript

//Include angular-ui dependency in resources on the side and as 'ui'
angular.module('myApp', [])

.controller("MyCtrl", function ($scope) {
    $scope.test = {
        test: ['Lorem Ipsum1', 'Lorem Ipsum2', 'Lorem Ipsum3']
    };
})

.directive('json', function () {
    return {
        restrict: 'E',
        transclude: true,
        template: '<pre>{{ content | json}}</pre>',
        compile: function (element, attr, transclusionFunc) {
            return function (scope, iterStartElement, attr) {
                var $origElement = transclusionFunc(scope);
                var content = $origElement.html();
                scope.content = scope.$eval(content);
            };
        }
    };
})
.directive('tel', function () {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: '<a href="tel:{{cleanNum}}">{{num}}</a>',
        compile: function (element, attr, transclusionFunc) {
            var invalidCharsRegex = /[^\d]/g; // Only numbers are allowed            
            return function (scope, iterStartElement, attr) {
                var $origElement = transclusionFunc(scope);
                var num = $origElement.text();
                var cleanNum = num.replace(invalidCharsRegex, "");
                scope.num = num;
                scope.cleanNum = cleanNum;
            };
        }
    };
})
.directive('email', function () {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: {},
        template: '<a href="mailto:{{address}}">{{text}}</a>',
        compile: function (element, attr, transclusionFunc) {
            return function (scope, iterStartElement, attr) {
                var $origElement = transclusionFunc(scope);
                scope.address = $origElement.parent().find('address').text();
                scope.text = $origElement.parent().find('text').text();
            };
        }
    };
});