如何在按钮单击上创建元素? [英] How to create an element on button click?

查看:45
本文介绍了如何在按钮单击上创建元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击按钮时,我想动态创建一个元素.我是否必须为此使用 ng-click 或指令?

I want to create dynamically an element when I click on a button. Do I have to use ng-click or a directive for that?

这是我要实现的目标的 JSFIDDLE 使用jQuery:

Here is a JSFIDDLE of what I'm trying to achieve using jQuery :

HTML:

<button id="myButton">Click Me</button>
<div id="container"></div>

JS:

$("#myButton").on("click", function() {
    $("#container").append('<div class="box"></div>');
});

此外,这是我所拥有的基础 JSFIDDLE 到目前为止,如果您想要一个angularjs解决方案,请继续进行工作.

Also, here is a base JSFIDDLE, of what I have so far, to work on if you want for an angularjs solution.

警告:

  • 请避免使用使用 ng-repeat 的控制器的解决方案.上面的代码是一个简化的示例.创建的元素不会以列表形式出现,因为我将拖动指令附加到它们上.
  • Please avoid a solution with a controller using ng-repeat. The code above is a simplified example. The created elements won't be as a list, because I'll attach a drag directive to them.

推荐答案

我必须为此使用ng-click还是指令?

Do I have to use ng-click or a directive for that?

要创建新元素,我将使用 $ compile .我强烈建议仅在指令中执行任何DOM操作.您可以通过 ng-click 指令触发附加过程,也可以使用 bind

To create new element I would use $compile. Any DOM manipulations I strongly recommend to do in directives only. You can trigger appending process through ng-click directive or to use bind like:

 element.bind("click", function(e){
      // do stuff here
   });

类似的东西:

 demo.directive("boxCreator", function($compile){   
      return{
        restrict: 'A',
        link: function(scope , element){        
           element.bind("click", function(e){

            var childNode = $compile('<button ng-click="doStuff()" >new button</button>')(scope)
            element.parent().append(childNode);                   
           });

            scope.doStuff = function(){                   
              // do stuff
            }
        }
    }
   });

演示 小提琴

这篇关于如何在按钮单击上创建元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆