2015-04-24 133 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

相關問題