2015-04-24 134 views
0

我有一个items数组,它被ng-repeat用来渲染菜单, 和点击Add to cart按钮addItem()被调用。如何将对象传递给指令

目前我通过item-container指令name属性中选定项目的名称。 我应如何通过属性传递整个对象的directive

HTML代码段

<p ng-repeat = "item in items"> 
<item-container 
    startcounter = 1 
    resetter  = 'reset' 
    item = 'item' 
    name   = {{item.name}} > 
    {{item.name}} 
</item-container><br><br> 
</p> 

JS片断

.directive('itemCounter',function(){ 
return { 
controller: function() {return {}}, 
    restrict:'E', 
    scope:{ 
    item:"=", 
    resetter:"=" 
    }, 
transclude:true, 
    link:function(scope,elem,attr){ 

     scope.qty = attr.startcounter 
     scope.add = function(){ 

      scope.qty++; 
     } 
     scope.remove = function(){ 
      scope.qty--; 
     } 
     scope.addItem = function(){ 
      console.log(attr.item); 
      scope.$parent.addMsg(scope.qty,attr.name) 
      console.log("value when submitted:" + scope.qty + "name:"+ attr.name); 
      scope.qty = attr.startcounter; 
      scope.$parent.resettrigger(); 
     } 

     scope.$watch(function(attr){ 
      return attr.resetter 
     }, 
     function(newValue){ 
      if(newValue === true){ 
       scope.qty = attr.startcounter; 
      } 
     }); 


    }, 
    template:"<button ng-click='addItem();'>Add to cart</button>&nbsp&nbsp"+    
     "<button ng-click='remove();' >-</button>&nbsp"+ 
       "{{qty}}&nbsp" + 
       "<button ng-click='add();'>+</button>&nbsp&nbsp"+ 
     "<a ng-transclude> </a>" 


} 

回答

1

目前实际上你甚至没有传入看起来好像是name。所有传入魔术发生在这一部分:

scope:{ 
    resetter:"=" 
}, 

正如你可以看到,有一个name没有提及。你需要做的就是添加一个字段item,只是把它传递:

scope:{ 
    resetter:"=", 
    item: "=" 
}, 

然后,你可以做

<p ng-repeat = "item in items"> 
<item-container 
    startcounter = 1 
    resetter  = 'reset' 
    item   = item > 
    {{item.name}} 
</item-container><br><br> 
</p> 

而且我确信你不想在这里使用transclude 。看看templateUrl

+0

我已编辑代码以包含传递的对象。但是当我安慰它,它打印为'item'.Am我以正确的方式传递对象 – dreamer

+0

@dreamer你当前的代码应该会产生一个语法错误(你错过了一个''''),但除此之外请不要'对多个问题回收相同的问题。如果您有新问题,请提出新问题。 –

+0

我能够使用'scope.item'而不是'attr.item'来访问对象 – dreamer

相关问题