AngularJS nested directives

by Adam Mendoza

HTML

<div ng-app="myApp" ng-controller="MainCtrl">
    <label>
        <u>model: </u>
        <input type="text" ng-model="someValue" outer="tmpl.html"/>
        <hr/>
    </label>
    
    <script type="text/ng-template" id="tmpl.html">
        <inner test="123"></inner>
    </script>
    
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.js"></script>
</div>

JavaScript

(function (ng) {
    
    'use strict';
    
    var app = ng.module('myApp', []);
    
    app.controller('MainCtrl', [
        '$scope',
        function ($scope) {
            $scope.someValue = 'Hello, World!';
        }
    ])
    .directive('inner', function () {
        return {
            restrict: 'AE',
            replace: true,
            template: '<p>{{model || "N/A"}} (updated {{updateCounter}} times)</p>',
            scope: { model: '=ngModel' },
            link: function (scope, element, attrs) {
                scope.updateCounter = 0;
                scope.$watch('model', function (newValue, oldValue) {
                    if (!ng.isDefined(oldValue) && !ng.isDefined(newValue)) { return; }
                    scope.updateCounter++;
                });
            }
        };
    })
    .directive('outer', [
        '$templateCache',
        '$compile',
        function ($templateCache, $compile) {
            return {
                restrict: 'AE',
                scope: {},
                link: function (scope, element, attrs) {
                    var template = $templateCache.get(attrs.outer).replace(/[\r\n]+/gm, '');
                    var compiled = $compile(template)(scope);
                    element.parent().append(compiled);
                }
            };
        }
    ]);
    
})(angular);