2016-07-14 14 views
0

私の要件は、parentディレクティブからchildディレクティブ関数を呼び出すことです。現在、パブリッシュ・サブスクライブ・パターンを実装しています。子ディレクティブは何らかのイベントを購読し、親ディレクティブに対してトリガーを行います。 publish subscribeは$ .callbacksで実装されています角双方向関数バインドのベストプラクティス

これ以外の方法はブロードキャストを使用することです。あるいは、子ディレクティブが変数を監視していて、この変数を親変数に変更することができます。

親ディレクティブには多くの子イベントが含まれており、すべてを通過させたくないため、ブロードキャストは使用しませんでした。

私たちは、これが

directives.directive('twoWayBind', function() { 
    return { 
     restrict: "E", 
     transclude: true, 
     templateUrl: 'app/twoWayBindFunction.html', 
     scope: { 
      twoWayBinding: '=' 
     }, 
     controller: 'twoWayBindFunctionController', 
     bindAsController: true, 
     controllerAs: 'vm', 
     link: function (scope, element, attrs, controller) { 
     } 
    }; 
}); 


controllers.controller('twoWayBindFunctionController', ['$scope', function (scope) { 
    var vm = this; 
    vm.scope = scope; 

    scope.twoWayBinding = function() { 
     console.log('twoway bind'); 
    }  
}]); 

を結合双方向機能を使用している私たちは、親スコープからtwoWayBinding関数を呼び出すことができます実装することができます別の方法があります。

私はベストプラクティスを理解したいと思います。

答えて

1

親ディレクティブのオブジェクトを子に渡すのが最善の方法です。 そのオブジェクトへの子ディレクティブの関数を追加し、それを親から呼び出します。

app.directive('parent', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      buttonCaption: '@' 
     }, 
     bindToController : true, 
     controllerAs : 'vm', 
     template: "<button ng-click='vm.twoWayObject.childFunc()'>{{vm.buttonCaption}}</button><child two-way-obj='vm.twoWayObject'></child>", 
     controller: function($scope) { 
      var vm = this;  
      vm.twoWayObject = {}; 
     }, 

     link: function() {    
     } 
    } 
}); 

app.directive('child', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      twoWayObj: '=' 
     }, 
     bindToController : true, 
     controllerAs : 'vm', 
     template: "<h1>Chuchi</h1>",    
     link: function() {    
     }, 
     controller: function($scope){ 
      var vm = this; 
      vm.twoWayObj.childFunc = function(){ 
       alert('child function called'); 
      } 
     } 
    } 
}); 

A add a Fiddleを例にとります。この質問に

ルック(最初の答え):

How to call a method defined in an AngularJS directive?

関連する問題