Angular: Empty Fiddle

http://angularjs.org/

by Varun Krishna P

HTML

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap.no-icons.min.css" rel="stylesheet"></link>
</head>
<body>
<div ng-controller="appCtrl">
    <h4 ng-show="bTreeDataSet">Click below button to remove all the data and then check the DOM, You will find that all the previous elements are removed!</h4>

    <button class="btn btn-primary" ng-click="toggleData()">{{btnText()}}</button><br />    
  <tree val="treeData"></tree>
</div>
</body>
</html>

CSS

.btn { margin:20px; }

JavaScript

angular.module('components', []);
angular.module('App', ['components']);
angular.module('components')
    .directive('tree', function ($compile) {
    return {
        restrict: 'E',
        terminal: true,
        scope: { val: '=', parentData:'=', position:"@" },
        link: function (scope, element, attrs) {
            var template = '<span>{{val.text}}</span><button ng-click="deleteMe()" ng-show="val.text">delete</button>';
            if (angular.isArray(scope.val.items)) {
                newElement = template += '<ul class="indent"><li ng-repeat="item in val.items"><tree position="{{$index}}" val="item" parent-data="val.items"></tree></li></ul>';
            }
            scope.deleteMe = function(index) {  
                scope.val = {};
                if(scope.parentData) {                	
                	scope.parentData.splice(scope.position,1);                	
                }
                
    		};
            var newElement = angular.element(template);
            $compile(newElement)(scope);
            element.replaceWith(newElement);            
        }
    }
});

function appCtrl($scope) {
    var treeData = {
        "text": "root",
        "items": [{
            "text": "Furniture",
                "items": [{
                "text": "Tables & Chairs"
            }, {
                "text": "Sofas",
                    "items": [{
                    "text": "Tables & Chairs"
                }, {
                    "text": "Sofas"
                }]
            }, {
                "text": "Occasional Furniture"
            }]
        }, {
            "text": "Decor",
                "items": [{
                "text": "Bed Linen"
            }, {
                "text": "Curtains & Blinds"
            }, {
                "text": "Carpets"
            }]
        }, {
            "text": "Storage",
                "items": [{
                "text": "Wall Shelving"
            }, {
                "text": "Floor Shelving"
    ...