silvesterprabu
silvesterprabu

Reputation: 1457

how to append div into one div using angularjs

 <div data-ng-controller="maincontrol">
   <div class="main">
   </div>
  <button data-ng-click="submit()">click</button>
 </div>

when i click on click button i want to append one div within main div . i want to append one new div (dynamically)for each and every click .also i want to find whether children div exist or not .

i will do like this in jquery

$('main').append();

i will pass div within append();

but how to do by using angular..js ?

Upvotes: 13

Views: 43120

Answers (2)

charlietfl
charlietfl

Reputation: 171669

It's generally best to create a directive for DOM manipulation ( many other uses for directives also).

Within a directive you have access to the angular.element . If jQuery is installed before angular.js in page, this is a jQuery object, otherwise it is a jqLite object that has many jQUery compatible methods.

Very simple example:

 <button data-ng-click="submit()" my-directive>click</button>
app.directive('myDirective',function(){
     return function(scope, element, attrs){
          element.click(function(){
               element.parent().find('.main').append('<div>Some text</div>')
           })
      }
})

Read up on directives and angular.element

Upvotes: 15

Luc
Luc

Reputation: 505

Using a directive could be a solution, but it's still too close to jQuery. When you play with Angular, you have to think differently.

jQuery is procedural.

1- I am finding an element in the dom

2- I am doing some stuff

3- I am adding, removing, updating elements in the dom

angular is declarative

  • You define your data

  • You define how your data should be displayed (using ng-repeat, ng-class, etc..)

then..

  • when you are playing with your data, the view is automatically updating.

If you want to play correctly with angular you should maybe do something like:

Template:

 <div class="main">
    <div ng-repeat="stuff in stuffs"><h1>{{stuff.title}}</h1> <p>{{stuff.content}}</p></div>
 </div>

Controller:

function MainCtrl() {
    $scope.stuffs = [];
    $scope.submit = function() {
       $scope.stuffs.push({title: 'Hello', content: 'world'});
    }
}

Upvotes: 25

Related Questions