Search code examples
javascriptangularjsangular-ngmodel

$watch for ng-model changes


i have the following markup

<li ng-repeat="ticket in tickets">
 <span>{{ticket.name}} - {{ticket.price}}</span>&nbsp;
 <input type="number" 
  value="1" 
  ng-disabled="!ticket.selected" 
  size="2" 
  style="width:34px;" 
  ng-change="ticket.quantity" 
 ng-model="ticket.quantity"/>
 <input type="checkbox" 
  name="choose" 
  ng-click="addToCart($event)" 
  ng-model="ticket.selected" 
  ng-if-false="false" 
  ng-if-true="true" 
  value="{{ticket.id}}"/>
</li>

then i have this on the addCart()

$scope.addToCart() = function(){ 

var template = '<fieldset id="ticket-'+this.ticket.id+'">' +
     '<input type="hidden" name="item_name_'+$scope.counter+'" value="'+this.ticket.name+'">' +
     '<input type="hidden" name="amount_'+$scope.counter+'" value="'+this.ticket.price+'">' +
     '<input type="hidden" name="on0_'+$scope.counter+'" value="quantity">' +
     '<input type="hidden" name="os0_'+$scope.counter+'" value="'+this.ticket.quantity+'"></fieldset>',
     $el = angular.element('#payform').append(template).find('input[name=os0_' + $scope.counter +']');
     $scope.$watch(this.ticket.quantity,function(){
        console.log(this, 'this', arguments);
        console.log('ticket',ticket);
        console.log($el.attr('name'));
     })
     return false;
}

I'm trying to dynamically watch for changes in the passed model to update the dynamically created form elements.

How can I achieve this and how heavy is it to keep adding and removing the event if the element no longer exists?


Solution

  • You are heading in the hardest direction. You should add this template at your view using ng-repeat, not creating elements inside the controller, whats represent the worst pratice ever. You should add this tickets inside an array, addedTickets for exemple and let AngularJS do the hardest job: render it dinamically!

    For Exemple:

    VIEW

    <input type="checkbox" 
     name="choose" 
     ng-click="addToCart(ticket, $index)" 
     ng-if-false="false" 
     ng-if-true="true" 
     ng-model="ticket.selected" />
    
    <fieldset id="ticket-{{t.id}}" ng-repeat="t in addedTickets">
     <input type="hidden" name="item_name_{{$index}}" ng-model="t.name">
     <input type="hidden" name="amount_{{$index}}" ng-model="t.price">
     <input type="hidden" name="on0_{{$index}}" ng-model="t.quantity">
    </fieldset>
    

    CONTROLLER

    $scope.addToCart(ticket, index) {
     if(ticket.selected) 
       $scope.addedTickets.push({name: ticket.name, quantit: ticket.quantity, /*etc*/});
     else
       //delete it
    }