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>  "+
"<button ng-click='remove();' >-</button> "+
"{{qty}} " +
"<button ng-click='add();'>+</button>  "+
"<a ng-transclude> </a>"
}
我已編輯代碼以包含傳遞的對象。但是當我安慰它,它打印爲'item'.Am我以正確的方式傳遞對象 – dreamer
@dreamer你當前的代碼應該會產生一個語法錯誤(你錯過了一個''''),但除此之外請不要'對多個問題回收相同的問題。如果您有新問題,請提出新問題。 –
我能夠使用'scope.item'而不是'attr.item'來訪問對象 – dreamer