2017-05-20 4 views
0

アンカーのギャラリを作成するアンカータグにng-repeatを使用するテンプレートを使用するディレクティブがあります。各アンカーには、クリック時に親コントローラ機能を呼び出すng-clickもあります。この関数には、ng-repeat項目が渡されます。ディレクティブテンプレートからコントローラに渡された場合のng-repeat変数

問題:親コントローラのメソッド内でアクセスするこのアイテムはここ

定義されていませんが、似たような状況

<testdirective func="show(x)" items="buttons"></testdirective> 

http://plnkr.co/edit/43aNqFS71Jn9vOdh6AG2?p=preview

答えて

1

あなたが作る必要がある2つの変更があります。あなたのindex.htmlを

あなたの関数にrefrenceします

template: '<button ng-repeat="item in items" ng-click="func()(item)" id="submit" />{{item}}</button>', 

お知らせNGの変化:

<testdirective func="show" items="buttons"></testdirective> 

とあなたのtestdirectiveではそうのようなあなたのテンプレートを変更 -click - 最初の括弧は、関数自体への参照を取得することであり、第2は、パラメータを使用して関数を呼び出すことです。

私はまた、あなたのplunkerのフォークを作った: http://plnkr.co/edit/nECPbL8YoToi0jP9HJHQ?p=preview

それはあなたが、私は理解して

+1

素晴らしい! :)このトリックはどこから手に入れましたか?私は何度も調べて、このようなパラメータの受け渡しを参照していませんでした。どうもありがとう。 – RaghaveShukla

0

をシミュレートするためのテストシナリオであるあなたのディレクティブは、コントローラに結合しなければなりません次のように変更してください。

app.directive("testdirective", function() { 
    return { 
    restrict: "E", 
    controller: 'testController', 
    template: '<button ng-repeat="item in items" ng-click="show(item)" id="submit" />{{item}}</button>', 
    scope: { 
     items: "=", 
     func: '&' 
    } 

    }; 
}); 

DEMO

// Code goes here 
 

 
var app = angular.module('test', []); 
 

 
app.controller('testController', function($scope) { 
 

 
    $scope.buttons = ['b1', 'b2', 'b3', 'b4', 'b5']; 
 

 
    $scope.show = function(x) { 
 
    alert(x); 
 
    } 
 
}) 
 

 

 
app.directive("testdirective", function() { 
 
    return { 
 
    restrict: "E", 
 
    controller: 'testController', 
 
    template: '<button ng-repeat="item in items" ng-click="show(item)" id="submit" />{{item}}</button>', 
 
    scope: { 
 
     items: "=", 
 
     func: '&' 
 
    } 
 

 
    }; 
 
});
<!DOCTYPE html> 
 
<html ng-app='test'> 
 

 
    <head> 
 
    <script data-require="[email protected]*" data-semver="1.3.0-rc.1" src="https://code.angularjs.org/1.3.0-rc.1/angular.js"></script> 
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body> 
 
    <div ng-controller="testController"> 
 
    <h1>Hello Plunker!</h1> {{ testValue }} 
 
    
 
    <testdirective func="show(x)" items="buttons"></testdirective> 
 
    </div> 
 
</body> 
 
</html>

+0

はいを​​達成するために望んだ場合を教えているが、そのコントローラに結合しているので、これは、再利用可能なディレクティブではありませんしてくださいではない。 – RaghaveShukla

+0

再利用できないとはどういう意味ですか?あなたはそれを再利用することはできません – Sajeetharan

+0

あなたは明示的にそれを 'controller: 'testController'にバインドしています。 – RaghaveShukla

関連する問題