让ngClick处理动态字段

问题描述 投票:1回答:1

我似乎无法弄清楚为什么ng-click指令不适用于复制的DOM元素。

这里是小提琴:http://jsfiddle.net/BkRqa/4/

我可以单击+ Insert new fieldset,但是删除添加的字段集的按钮不起作用。

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();
        }
    }]);
})();
javascript jquery html angularjs dom
1个回答
4
投票

克隆的字段将插入到DOM中,但不是由Angular编译的。这意味着它们包含的指令尚未解析,因此ng-click在克隆的元素上不起作用。因此,编译应手动完成:

© www.soinside.com 2019 - 2024. All rights reserved.