我有一个items
数组,ng-repeat用它来渲染菜单,
点击Add to cart
按钮addItem()
即可。
目前,我将所选项目的名称作为name
指令中的item-container
属性传递。
如何将整个对象通过属性传递给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>"
}
答案 0 :(得分: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