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