Reputation: 21
I want to select a HTML element and append it to another div on a click of a button using Angular2. Startup HMTL
<div class="parent">
<ul class="level1">
<li>
<div class="otherdiv">
This is a test
<button md-raised-button type="button" color="primary">Clone</button>
</div>
</li>
</ul>
When the button is clicked I expect to have following structure
<div class="parent">
<ul class="level1">
<li>
<div class="otherdiv">
This is a test
<button md-raised-button type="button" color="primary">Clone</button>
</div>
<ul class="level2">
<li>
<div class="otherdiv">
This is a test
<button md-raised-button type="button" color="primary">Clone</button>
</div>
</li>
</ul>
</li>
</ul>
Not sure how can I achieve this. Any help appreciated. Thanks
Upvotes: 0
Views: 321
Reputation: 3541
You can use clone()
in jquery.
Here is the code:
$('button').click(function() {
$("#level1").clone().attr('id', 'level2').insertAfter("#level1");
});
<div class="parent">
<ul id="level1">
<li>
<div class="otherdiv">
This is a test
<button md-raised-button type="button" color="primary">Clone</button>
</div>
</li>
</ul>
Using angluarJs also we can do the same by using ng-repeat
.You can repeat every time by adding the number.
var app = angular.module('myapp', []);
app.controller('ctrlParent', function($scope) {
$scope.myNumber = 1;
$scope.myFun = function() {
$scope.myNumber = $scope.myNumber + 1;
}
$scope.getNumber = function(num) {
return new Array(num);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myapp">
<div ng-controller="ctrlParent">
<ul>
<li ng-repeat="i in getNumber(myNumber) track by $index"><span>{{$index+1}}</span>
<button ng-click="myFun()">Click to CLone
</button>
</li>
</ul>
</div>
</div>
Upvotes: 1