Getting ngClick to work on dynamic fields

Problem

I can't seem to figure out why the ng-click directive isn't working on copied DOM elements.

Here is the fiddle: http://jsfiddle.net/BkRqa/4/

I can click on + Insert new fieldset, but the buttons to remove added fieldsets are not working.

HTML

<div ng-app="myApp">
    <div ng-controller="myController">
        <div id="education">
            <button class="add-button" ng-click="cloneField($event)">+ Insert new field</button>
            <!-- I want to make copies of .control-fieldset -->
            <div class="control-fieldset">
                <div class="control-group">
                    <label for="name_0">School</label>
                    <input type="text" name="name[0]" id="name_0">
                    <!-- I want to remove copies of .control-fieldset -->
                    <button class="remove-button" ng-click="removeField($event)">-</button>
                </div>
            </div>
        </div>
    </div>
</div>

Controller

(function () {
    var myApp = angular.module('myApp', []);

    myApp.controller('myController', ['$scope', function ($scope) {

        $scope.cloneField = function (event) {
            var fieldHtml = $(event.target).parent().find(".control-fieldset").first().clone();
            $(event.target).parent().append(fieldHtml);
        };

        $scope.removeField = function (event) {
            $(event.target).remove();
        }
    }]);
})();
Problem courtesy of: Fred Fickleberry III

Solution

The cloned fields are being inserted into the DOM but not compiled by Angular. This means that the directives they contain have not been parsed and so the ng-click is not working on the cloned elements. So the compile should be done manually:

$scope.cloneField = function (event) {
    var fieldHtml = $(event.target).parent().find(".control-fieldset").first().clone();
    // Compile, then append the compiled element instead of the uncompiled
    var compiledElement = $compile(fieldHtml)($scope);
    $(event.target).parent().append(compiledElement);
};

Don't forget to inject the $compile service into the controller.

Also, since the button is the target of the event, you'll need to change your remove function to target the button's parent to remove any given cloned fieldset:

$scope.removeField = function (event) {
    $(event.target).parent().remove();  // Remove the whole cloned element
}

Demo: Here is a fiddle

Solution courtesy of: sh0ber

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.