如何动态创建具有特定类的角度div? [英] how to dynamically create a div in angular having a certain class?

查看:44
本文介绍了如何动态创建具有特定类的角度div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在单击按钮时创建一个div:

I want to create a div on click of a button:

div应该是这样的:

the div should be like this:

<div class="my-blur"><div>

我正在这样做:

$scope.showFloatingActioButtons = function() {
        var newEle = angular.element('<div class="my-blur"></div>');
        $compile(newEle)($scope);
}

推荐答案

您快到了……您只需要将该元素添加到DOM中即可.

You are almost there... you just need to add that element to the DOM somehwere.

angular.element('someselector-or-dom-element').append(newEle);

除非您在新元素上具有绑定或指令,否则没有理由对其进行编译.

And unless you have bindings or directives on your new element, there is no reason to compile it.

我添加了一个正在运行的示例以帮助消除任何混乱.

I've added a running example to help clear up any confusion.

var app = angular.module('my-app', []);

function MyCtrl(){}
MyCtrl.prototype = {
  addElement:function(){
    var newEle = angular.element("<div class='red'></div>");
    var target = document.getElementById('target');
    angular.element(target).append(newEle);
  }
};

app.controller('myCtrl', MyCtrl);

.red{
  margin: 10px;
  height:20px;
  background-color:red;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<div ng-app="my-app" ng-controller="myCtrl as $ctrl">
  <button type="button" ng-click="$ctrl.addElement()">Add Element</button>
  <div id="target"></div>
</div>

这篇关于如何动态创建具有特定类的角度div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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