Elfayer
Elfayer

Reputation: 4561

How to create an element on button 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?

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

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

Warn:

Upvotes: 0

Views: 7130

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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

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

Something like that:

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

Demo Fiddle

Upvotes: 4

sylwester
sylwester

Reputation: 16498

http://jsbin.com/cuciyu/2/edit

JS

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

app.directive("addDiv", function($compile){   
          return{
            restrict: 'AE',
            link: function(scope , element,attr){        
               element.bind("click", function(e){ 
               var container =   angular.element(document.querySelector("#container"));
               var childNode = $compile('<div class="box">BOX DIV</div>')(container);
               container.append(childNode);

               });
            }
        };
       });

    app.controller('firstCtrl', function($scope){


    });

HTML:

  <body ng-app="app">
  <div ng-controller="firstCtrl">
    <button add-div>Click Me</button>
        <div id="container"></div>
      </div>
</body>

Upvotes: 2

Related Questions