2016-07-14 53 views
0

我的要求是從父指令調用子指令函數。目前我們已經實現了發佈 - 訂閱模式。 Child指令訂閱某個事件,並且我們對父指令進行觸發。 發佈訂閱是通過$ .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以示例添加一個Fiddle

看這個問題(第一個答案):

How to call a method defined in an AngularJS directive?