Angularjs addmore directive and scope management -
i trying create directive has addmore button.
in controller have tickets
obj empty. trying add new tickets (multiple) obj while clicking "add tickets".
what need
- each ticket should increment 1.
- the ticket
price
should updated intickets
array whenprice
updated in input box (two way binding). - should able update
quantity
controller or directive should update in quantity input (one way binding).
i have created plunker , appreciated, have spend lot of time in this.
fancy solution components
i forked plunker here component version.
when can, recommand use of components on directives.
i splitted in 2 components, that's way easier separate functionnalities. 1 components list, , other 1 item representation.
tickets component
it handles ng-repeat on components, add button , sum functions.
app.component('tickets', { template: '<div ng-repeat="ticket in $ctrl.tickets">#{{ticket.id}}<ticket ng-change="$ctrl.recompute()" assign="$ctrl.assign" ng-model="ticket"/></div><hr><button ng-click="$ctrl.addone()">add one</button><br>total price : {{$ctrl.price}}<br>total quantity : {{$ctrl.quantities}}', controller: class ctrl { $oninit() { this.tickets = []; this.price = 0; this.quantities = 0; } count() { return this.tickets.length; } addone() { this.tickets.push({ id: this.count(), price: 0, color: 'red', quantity: 1 }); this.recompute(); } recompute() { this.price = 0; this.quantities = 0; this.tickets.foreach((ticket) => { this.price += ticket.price; this.quantities += ticket.quantity; }); } assign(ticket) { console.log("ticket assigned : ", ticket); } } });
ticket component
it handles representation , actions one ticket.
app.component('ticket', { template: '<div><label>quantity</label><input type="number" ng-model="$ctrl.ticket.quantity" ng-change="$ctrl.ngchange"/><br><label>price</label><input type="number" ng-model="$ctrl.ticket.price" ng-change="$ctrl.ngchange"/><br><button ng-click="$ctrl.assignme()">assign</button></div>', bindings: { ngmodel: '=', ngchange: '<', assign: '<' }, controller: class ctrl { $oninit() { this.ticket = this.ngmodel; } assignme() { this.assign(this.ticket); } addone() { this.tickets.push({ price: 0, color: 'red', quentity: 0 }); } } });
let me if want version directive.
Comments
Post a Comment