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);
}
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With