在ng-repeat中添加一个新指令

时间:2014-09-03 13:02:12

标签: javascript angularjs

我有一组数据,使用ng-repeat中的指令显示。当用户单击按钮时,它将在此数组中添加一个新对象,因此必须执行该指令的新实例。我的HTML目前:

<ul>
  <li ng-repeat="c in commissions" commission="c.commission" index="{{$index}}"></li>
</ul>

当用户点击&#34;添加&#34;按钮,执行以下功能(coffeescript):

$scope.newCommission = function() {
  var commission;
  commission = {
    new_commission: true
  };
  return $scope.commissions.push(commission);
};

我的指令atm:

var Commission;

Commission = function() {
  return {
    restrict: 'A',
    replace: true,
    templateUrl: '/assets/template/commission/list.html',
    controller: 'ProductEditCtrl',
    scope: {
      commission: '=',
      index: '@'
    },
    link: function(scope, el, attrs, ctrl) {
      var commission;
      commission = scope.commission;
      commission.index = scope.index;
      scope.editable = false;
      scope.changeType = function(type) {
        return commission.type = type;
      };
      scope.removeCommission = function() {
        return ctrl.deleteCommission(commission.index, commission.id);
      };
      scope.saveCommission = function() {
        var obj;
        obj = {
          seller_id: commission.seller.id,
          type: commission.type,
          value: commission.value
        };
        ctrl.changeCommission(commission.id, obj);
        return scope.editable = false;
      };
      return scope.turnEditable = function() {
        return scope.editable = true;
      };
    }
  };
};

angular.module(&#39; horus.products&#39;)。指令(&#39;佣金&#39;,佣金);

所以,这会发生什么,我的列表中会添加一个new,它会从我的指令中编译模板,但它会给我一个错误:

  

TypeError:无法设置属性&#39; index&#39;未定义的       在链接(http://horus.dev/assets/app/modules/products/directives/commission.js?body=1:17:26)       在http://horus.dev/assets/angular/angular.js?body=1:7036:44       at nodeLinkFn(http://horus.dev/assets/angular/angular.js?body=1:6634:13)       在delayedNodeLinkFn(http://horus.dev/assets/angular/angular.js?body=1:6856:11)       在compositeLinkFn(http://horus.dev/assets/angular/angular.js?body=1:6029:13)       在publicLinkFn(http://horus.dev/assets/angular/angular.js?body=1:5924:30)       at boundTranscludeFn(http://horus.dev/assets/angular/angular.js?body=1:6049:21)       在controllersBoundTransclude(http://horus.dev/assets/angular/angular.js?body=1:6655:18)       在ngRepeatAction(http://horus.dev/assets/angular/angular.js?body=1:20345:15)       at Object。$ watchCollectionAction [as fn](​​http://horus.dev/assets/angular/angular.js?body=1:12269:13

为什么会发生这种情况的任何想法,我该如何解决这个问题?我这样做的方式是在ng-repeat中添加新指令的最佳方法吗?

1 个答案:

答案 0 :(得分:0)

我找到了我的bug的解决方案,这是由于我定义了插入到我的数组中的对象的方式引起的问题..所以哑巴哈哈