简体   繁体   English

AngularJs指令用函数追加和删除DOM元素

[英]AngularJs directive to append and remove DOM element with function

I'm trying to create a directive to append a new html element to the DOM and also to remove it. 我正在尝试创建一个directive ,将新的html element附加到DOM并删除它。

The logic to append and remove is already working, except to remove the element when clicking on a button. 除了在单击按钮时删除element ,添加和删除的逻辑已经起作用。 Right now I'm only able to remove it when pressing the esc key. 现在我只能在按下esc键时将其删除。 I have this directive here: 我在这里有这个指令:

function scLight() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            var myEl = '<div sc-light id="lightBox" class="debugModal"><h1>Tests</h1><button ng-click="removeEl()">Close</button></div>',
                ngEl = angular.element(myEl);

            scope.insertEl = function() {
                // angular.element(document.body).append(ngEl); //Append to body
                element.append(ngEl); //Append to element
            }

            scope.removeEl = function() {
                var lightBoxEl = document.getElementById("lightBox"),
                    ngLightBoxEl = angular.element(lightBoxEl);
                ngLightBoxEl.remove();
            }

            document.addEventListener("keyup", function(event) {
                if(event.which == 27) {
                    return scope.removeEl();
                }
            });
        }
    }
}

If I click the button to insert the new element , it works. 如果我单击按钮插入新element ,它可以工作。 If I press esc the element is removed. 如果按escelement被删除。 But if I press the button to Close the element, which has this "ng-click="removeEl()" , nothing happens. 但是,如果我按下按钮关闭元素,其中包含"ng-click="removeEl()" ,则没有任何反应。

How can I solve this problem? 我怎么解决这个问题?

You never compiled HTML element, so ng-click attribute doesn't mean anything for Angular. 你从不编译HTML元素,因此ng-click属性对Angular没有任何意义。

You should do this: 你应该做这个:

scope.insertEl = function() {
  element.append(ngEl);
  $compile(ngEl)(scope);
}

For this, remember to inject $compile into directive: 为此,请记住将$compile注入指令:

function scLight($compile) { /* ... */ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM