0

All:

I am pretty new to AngularJS, my question is how to dynamically add elements to page within a scope.

Like:

<div id="cnt" ng-controller="main">
    <button>Add more</button>
</div>

<script>
  app.controller("main", function($scope){
        $scope.name = "hello";
  });

$("button").on("click", function(){
  var div = $("#cnt").append("div");
  div.html("{{name}}");
});
</script>

What It is supposed to happen is the newly added div will have the name auto binded( shown as "hello"). But when I click the button, it only add more div with "{{name}}" in it.

I wonder what is the best way to do this?

Kuan
  • 11,149
  • 23
  • 93
  • 201

1 Answers1

1

Why don't you use ng-repeat? You most likely have a very structured element that needs to be dynamically added. Also, you should use ng-click instead of binding to the DOM $(button). What happens when you have two buttons serving two different purpose?

So your HTML would be:

<div id="cnt" ng-controller="main">
    <button ng-click="addMore()">Add more</button>

    <div ng-repeat="element in elements track by $index">
        <h1>{{ element.title }}</h1>
        <p>{{ element.body }}</p>
    </div>
</div>

Then your app would be:

app.controller("main", function($scope) {
    // Initialize the variable as an empty array
    $scope.elements = [];

    // Instead of binding to the button selector, use `ng-click`
    // in your HTML and add the function here
    $scope.addMore = function() {

        // Create a new object with whatever attributes you need 
        var element = {
            title: 'Element Title',
            body: 'Hello World!'
        }
        // Push it to the $scope.elements array
        // ng-repeat will loop through all the elements in the array 
        // It's just like foreach()
        $scope.elements.push(element);
    }
});
Kousha
  • 32,871
  • 51
  • 172
  • 296
  • Thanks for help. Actually I am not gonna add a lot of divs, the code above is just for test purposes, the only thing I want to figure out is how to dynamically bind data to newly added element within certain scope and Coule you tell me why the way I use not work? Thanks! – Kuan Nov 13 '14 at 18:16
  • The way you used does work, it's just not the Angular way - actual DOM manipulation is the jQuery way which is considered bad. I suggest you read this page: http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background – Kousha Nov 13 '14 at 18:21
  • Furthermore, using `ng-repeat` just makes it a whole lot easier to work it. It has cleaner syntax. And most importantly, when you want to remove DOMs, instead of finding out which DOM you need to remove, you just have to `splice` that element from the array and voila, you have removed something! – Kousha Nov 13 '14 at 18:23
  • thanks, I will read that post. But I wonder how can you make my code works, on my side, the newly added element can not show "hello" – Kuan Nov 13 '14 at 18:28