angularjs - How to dynamically add element with data binding -



angularjs - How to dynamically add element with data binding -

all:

i pretty new angularjs, question how dynamically add together elements page within 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 supposed happen newly added div have name auto binded( shown "hello"). when click button, add together more div "{{name}}" in it.

i wonder best way this?

why don't utilize ng-repeat? have structured element needs dynamically added. also, should utilize ng-click instead of binding dom $(button). happens when have 2 buttons serving 2 different purpose?

so html be:

<div id="cnt" ng-controller="main"> <button ng-click="addmore()">add more</button> <div ng-repeat="element in elements track $index"> <h1>{{ element.title }}</h1> <p>{{ element.body }}</p> </div> </div>

then app be:

app.controller("main", function($scope) { // initialize variable empty array $scope.elements = []; // instead of binding button selector, utilize `ng-click` // in html , add together function here $scope.addmore = function() { // create new object whatever attributes need var element = { title: 'element title', body: 'hello world!' } // force $scope.elements array // ng-repeat loop through elements in array // it's foreach() $scope.elements.push(element); } });

angularjs

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -