2016-11-24 6 views
1

親ディレクティブから子ディレクティブに値を渡したいとします。このシナリオでは、parentディレクティブには、childディレクティブのdivをクリックして実行し、childディレクティブからparentディレクティブの呼び出し関数にng-model値を渡す必要がある関数があります。関数バインディング '&'を使用して、あるディレクティブから別のディレクティブに値を渡します。

http://jsfiddle.net/Lvc0u55v/12543/

var myApp = angular.module('myApp', []); 
 
myApp.directive('parentDirective', function() { 
 
    return { 
 
    restrict: 'EA', 
 
    transclude: true, 
 
    template: '<div>Parent directive</div>', 
 
    link: function(scope) { 
 
     scope.someFunc = function(value) { 
 
     alert(value); 
 
     } 
 
    } 
 
    } 
 
}); 
 
myApp.directive('childDirective', function() { 
 
    return { 
 
    restrict: 'EA', 
 
    template: '<input type="text" ng-model="data.name"><button ng-click="issue(data.name)">Child Directive</button>', 
 
    scope: { 
 
     issue: '&' 
 
    } 
 
    } 
 
});
<div ng-app="myApp"> 
 
    <parent-directive ng-transclude> 
 
    <child-directive issue="someFunc()"></child-directive> 
 
    </parent-directive> 
 
</div>

JSfiddle link

答えて

0

私は適切なソリューションをごJSFiddleを更新しました。

親ディレクティブで関数をバインドするときにパラメータを指定する必要があります。

<child-directive issue="someFunc(value)"></child-directive> 

これらのパラメータを持つオブジェクトを子ディレクティブのキーとして渡します。

<button ng-click="issue({ value: data.name })">Child Directive</button> 
+1

Awsome !! 私の悪い私は:(親ディレクティブのパラメータを指定する しかし、なぜ私は?? {値:data.name}キーとしてパラメータを渡す必要はありませんでしただけdata.nameが機能しなかった理由は? –

+0

心配する必要はありません。これはかなり一般的なエラーです。それがAngularJSの仕組みです。 – Puigcerber

+0

おそらく[this](http://www.codelord.net/2016/05/13/understanding-angulars-and-binding/)は良い理由を説明する記事 – Puigcerber

関連する問題