我有以下标记

<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>


然后我在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;
}


我试图动态监视传递的模型中的更改以更新动态创建的表单元素。

如果元素不再存在,如何实现此目标以及继续添加和删除事件有多沉重?

最佳答案

您正在朝着最艰难的方向前进。您应该使用ng-repeat在视图中添加此模板,而不是在控制器内部创建元素,这代表有史以来最糟糕的实践。您应该将此票证添加到数组中,例如addedTickets,让AngularJS做最困难的工作:动态地渲染它!

举个例子:

视图

<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>


控制器

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

关于javascript - $观看ng-model的变化,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31325122/

10-11 20:17