5

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);
}

1 Answer 1

10

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>

Sign up to request clarification or add additional context in comments.

12 Comments

getting newEle.appendTo is not a function
Yeah, only available if you have jQuery... let me fix the anwer.
but i don't have jquery.
@lakshay - Updated the answer to take into account that you don't have jQuery.
Are you getting an error? Is your selector correct?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.