Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to dynamically create a div in angular having a certain class?

Tags:

angularjs

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

the div should be like this:

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

I am doing this:

$scope.showFloatingActioButtons = function() {
        var newEle = angular.element('<div class="my-blur"></div>');
        $compile(newEle)($scope);
}
like image 630
abhit Avatar asked Jan 20 '17 13:01

abhit


People also ask

How to add dynamic class in js?

To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript. Approach: The className property used to add a class in JavaScript.

How do I add a class in angular 10?

Add a Class based upon the conditionWe can directly pass true or false to add a class. As the key singleClass value is true class will be added to the div element. For example if we want to add a class name based upon multiple conditions, we can pass a conditional expression as an object value.


1 Answers

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>
like image 191
Josh Avatar answered Oct 06 '22 00:10

Josh