如何将对象传递给指令

时间:2015-04-24 16:29:12

标签: angularjs angularjs-directive

我有一个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>&nbsp&nbsp"+            
         "<button ng-click='remove();' >-</button>&nbsp"+
                 "{{qty}}&nbsp" +
                 "<button ng-click='add();'>+</button>&nbsp&nbsp"+
         "<a ng-transclude> </a>"


}

1 个答案:

答案 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