Dorota Dorota - 3 months ago 9
AngularJS Question

Copying a div on click in Angular

I'm trying to copy and paste a div when clicking a button using Angular.js. Here's my codepen: http://codepen.io/summerfreeze/pen/VjqJYW . I want the "add order line" button to add another .orderline div. I'm new to Angular and I obviously did some mistakes, because it doesn't work. What is wrong with the code?

$scope.orderlines=[]
$scope.orderline = '';
$scope.addline = function(){
$scope.items.push($scope.orderline);
};

Answer

I updated your code pen. That I did :

Change $scope.orderline to string from object. It now represent an order line. It used when user put values from form :

$scope.orderline = {};

Change binding on qty and total (now bind on $scope.orderline):

<input ng-model="orderline.quantity" placeholder="Quantity">
<div flex >{{orderline.quantity * selectedItem.price}}</div>

Change ng-repeat (now loop on orderlines and items are named lines) :

<div ng-repeat='line in orderlines'>
         {{line}}
     </div>

Finally, update addLine to copy order line in orderLines :

$scope.addline = function(){
    $scope.orderline.name = $scope.selectedItem;
    $scope.orderlines.push(angular.copy($scope.orderline)); 
};

Here the updated plunker http://codepen.io/anon/pen/NAJqZy

Comments