AngularJS -- Scope inheritance with displaced DOM elements

by vacationlabs

HTML

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<div ng-app="MyModule" ng-controller="MyController">
    <button type="button" ng-click="change_data()">Change qtip data</button>
    <div ng-repeat="d in data">
        <div qtip="">
            <a href="" qtip-target="">Click here to fire qtip</a>
            <div qtip-content="">
                <h4>{{ d.title }}</h4>
                <p>{{ d.content }}</p>
            </div>
    
        </div>
    </div>
</div>

JavaScript

var mod = angular.module('MyModule', []);

mod.controller('MyController', ['$scope', '$window', function($scope, $window) {
    $scope.data = [{
        'title' : 'Popover #1 title',
        'content' : 'Popover #1 content'
    }, {
        'title' : 'Popover #2 title',
        'content' : 'Popover #2 content'
    }];

    $scope.change_data = function() {
        $scope.data[0]={
        'title' : 'Popover #3 title',
        'content' : 'Popover #3 content'
        };
        $scope.data[1]={
        'title' : 'Popover #4 title',
        'content' : 'Popover #4 content'
        };
        
    };
}]);


mod.directive('qtip', function() {
    return {
        'restrict' : 'A',
        'scope' : true,
        'link' : function(scope, element, attrs) {
            console.log('I was called with', element.html());
            var qtip_content = element.find('[qtip-content]');
            qtip_content.appendTo('body').hide();
            element.find('[qtip-target]').click(function() {
                qtip_content.toggle();
            });
            scope.$on('$destroy', function() {
                console.log('scope was destroyed');
                qtip_content.remove();
            });
        }
    };
    
});