4

私が必要とするところまで私をほとんど惹きつけるこの質問が見つかりました。 Why doesn't ng-click work in my directive and how do I add a toggle class? 指令内のng-clickからコントローラ内の関数にデータを渡す

私のディレクティブテンプレート内でクリックすると、コントローラの機能が起動されます。 http://plnkr.co/edit/GorcZZppa8qcIKbQAg2v?p=preview

問題は、パラメータがに定義されていない私のコントローラ(項目)に戻ったということです。私は実際にコントローラ内で実行する関数で使用するために、ディレクティブ内の変数からデータを渡す必要があります。

指令テンプレートファイル

<div class="tsProductAttribute" 
     ng-class="{'tsProductAttribute--selected': selected}" 
     ng-click="toggleState(item)"> 

    <span class="tsProductAttribute-image"> 
     <img ng-src="{{variantImage}}"> 
    </span> 
    <span class="tsProductAttribute-desc">{{item.productName}}</span> 
    <select ng-model="variantImage"> 
     <option ng-repeat="variant in item.variants" value="{{variant.image}}">{{variant.name}} - {{variant.listprice.amount}}</option> 
    </select> 
    <span class="tsProductAttribute-price">{{item.variants[0].listprice.amount}} {{item.variants[0].listprice.entity}}</span> 
</div> 

指令

angular.module('msfApp') 
.directive('listitem', function() { 
    return { 
     templateUrl: 'assets/templates/directives/listitem.html', 
     restrict: 'E', 
     scope: { 
      'item': '=', 
      'itemClick': '&' 
     }, 
     link: function(scope, iElement, iAttrs) { 
      scope.selected = false; 
      scope.toggleState = function(item) { 
      scope.selected = !scope.selected; 
      scope.itemClick(item); 
      } 
     } 
    } 
}); 

指令実装

<listitem item="item" item-click="toggleInBasket(item)"></listitem> 
単離された範囲をディレクティブに関数を渡し、あなたがメソッド参照を渡す &(結合式)を使用しなければならない一方でコントローラ

$scope.toggleInBasket = function(item) { 
     $scope.basket.toggle(item); 

     console.log(basket.get()); 

    } 

(項目)で機能

答えて

6

未定義です。 item-clickでは、あなたはtoggleInBasket(item)

マークアップ

<listitem item="item" item-click="toggleInBasket(item)"></listitem> 

のようなコントローラメソッドに実際の呼び出しを述べなければならない。そしてディレクティブからメソッドを呼び出している間、あなたはscope.itemClick({item: item})

指令

angular.module('msfApp').directive('listitem', function() { 
    return { 
    templateUrl: 'listitem.html', 
    restrict: 'E', 
    scope: { 
     'item': '=', 
     'itemClick': '&' // & changed to expression binding 
    }, 
    link: function(scope, iElement, iAttrs) { 
     scope.selected = false; 
     scope.toggleState = function(item) { 
     scope.selected = !scope.selected; 
     scope.itemClick({item: item}); //changed call to pass item value 
     } 
    } 
    } 
}); 
としてそれを呼び出す必要があります

Demo here

+0

ありがとう、これはうまくいきました。私のライブコードで試してみましょう:) – Mcestone

+0

@mcestoneそれを聞いてうれしいです。ありがとう:-) –

+0

それは働いた!助けてくれてありがとう、本当に感謝しています。 – Mcestone

関連する問題