2016-07-14 3 views
0

나의 요구 사항은 parent 지시문에서 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?