13
 <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 ?

1

2 Answers 2

25

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'});
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It might be a old post, but this one doesn't answer the question ! the question is more about adding html elements rather than a list of items!
I find this answer to be a very smart way of using angular. thanks man
15

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

Comments

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.